From 8da09aed94e0c407f3c82450fa8268e6bff0f71b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= Date: Wed, 14 Jun 2023 00:19:09 +0800 Subject: [PATCH 01/66] Add allow-by-default lint for unit bindings This lint is not triggered if any of the following conditions are met: - The user explicitly annotates the binding with the `()` type. - The binding is from a macro expansion. - The user explicitly wrote `let () = init;` - The user explicitly wrote `let pat = ();`. This is allowed for local lifetimes. --- compiler/rustc_lint/messages.ftl | 3 + compiler/rustc_lint/src/lib.rs | 3 + compiler/rustc_lint/src/lints.rs | 7 ++ compiler/rustc_lint/src/unit_bindings.rs | 72 +++++++++++++++++++ tests/ui/closures/issue-868.rs | 1 + ...diverging-fallback-unconstrained-return.rs | 4 +- 6 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 compiler/rustc_lint/src/unit_bindings.rs diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 068f1372c0ec..b44aa77f2d4b 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -523,6 +523,9 @@ lint_undropped_manually_drops = calls to `std::mem::drop` with `std::mem::Manual lint_ungated_async_fn_track_caller = `#[track_caller]` on async functions is a no-op .label = this function will not propagate the caller location +lint_unit_bindings = binding has unit type `()` + .label = this pattern is inferred to be the unit type `()` + lint_unknown_gated_lint = unknown lint: `{$name}` .note = the `{$name}` lint is unstable diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 606e18866165..8e5b3690f8ef 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -85,6 +85,7 @@ mod redundant_semicolon; mod reference_casting; mod traits; mod types; +mod unit_bindings; mod unused; pub use array_into_iter::ARRAY_INTO_ITER; @@ -123,6 +124,7 @@ use redundant_semicolon::*; use reference_casting::*; use traits::*; use types::*; +use unit_bindings::*; use unused::*; /// Useful for other parts of the compiler / Clippy. @@ -203,6 +205,7 @@ late_lint_methods!( InvalidReferenceCasting: InvalidReferenceCasting, // Depends on referenced function signatures in expressions UnusedResults: UnusedResults, + UnitBindings: UnitBindings, NonUpperCaseGlobals: NonUpperCaseGlobals, NonShorthandFieldPatterns: NonShorthandFieldPatterns, UnusedAllocation: UnusedAllocation, diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 756899e50a8c..2b74123fed46 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -1845,3 +1845,10 @@ impl<'a> DecorateLint<'a, ()> for AsyncFnInTraitDiag { fluent::lint_async_fn_in_trait } } + +#[derive(LintDiagnostic)] +#[diag(lint_unit_bindings)] +pub struct UnitBindingsDiag { + #[label] + pub label: Span, +} diff --git a/compiler/rustc_lint/src/unit_bindings.rs b/compiler/rustc_lint/src/unit_bindings.rs new file mode 100644 index 000000000000..c80889f3ae75 --- /dev/null +++ b/compiler/rustc_lint/src/unit_bindings.rs @@ -0,0 +1,72 @@ +use crate::lints::UnitBindingsDiag; +use crate::{LateLintPass, LintContext}; +use rustc_hir as hir; +use rustc_middle::ty::Ty; + +declare_lint! { + /// The `unit_bindings` lint detects cases where bindings are useless because they have + /// the unit type `()` as their inferred type. The lint is suppressed if the user explicitly + /// annotates the let binding with the unit type `()`, or if the let binding uses an underscore + /// wildcard pattern, i.e. `let _ = expr`, or if the binding is produced from macro expansions. + /// + /// ### Example + /// + /// ```rust,compile_fail + /// #![deny(unit_bindings)] + /// + /// fn foo() { + /// println!("do work"); + /// } + /// + /// pub fn main() { + /// let x = foo(); // useless binding + /// } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Creating a local binding with the unit type `()` does not do much and can be a sign of a + /// user error, such as in this example: + /// + /// ```rust,no_run + /// fn main() { + /// let mut x = [1, 2, 3]; + /// x[0] = 5; + /// let y = x.sort(); // useless binding as `sort` returns `()` and not the sorted array. + /// println!("{:?}", y); // prints "()" + /// } + /// ``` + pub UNIT_BINDINGS, + Allow, + "binding is useless because it has the unit `()` type" +} + +declare_lint_pass!(UnitBindings => [UNIT_BINDINGS]); + +impl<'tcx> LateLintPass<'tcx> for UnitBindings { + fn check_local(&mut self, cx: &crate::LateContext<'tcx>, local: &'tcx hir::Local<'tcx>) { + // Suppress warning if user: + // - explicitly ascribes a type to the pattern + // - explicitly wrote `let pat = ();` + // - explicitly wrote `let () = init;`. + if !local.span.from_expansion() + && let Some(tyck_results) = cx.maybe_typeck_results() + && let Some(init) = local.init + && let init_ty = tyck_results.expr_ty(init) + && let local_ty = tyck_results.node_type(local.hir_id) + && init_ty == Ty::new_unit(cx.tcx) + && local_ty == Ty::new_unit(cx.tcx) + && local.ty.is_none() + && !matches!(init.kind, hir::ExprKind::Tup([])) + && !matches!(local.pat.kind, hir::PatKind::Tuple([], ..)) + { + cx.emit_spanned_lint( + UNIT_BINDINGS, + local.span, + UnitBindingsDiag { label: local.pat.span }, + ); + } + } +} diff --git a/tests/ui/closures/issue-868.rs b/tests/ui/closures/issue-868.rs index ce0a3c7ca526..df03b191a99e 100644 --- a/tests/ui/closures/issue-868.rs +++ b/tests/ui/closures/issue-868.rs @@ -1,5 +1,6 @@ // run-pass #![allow(unused_parens)] +#![allow(unit_bindings)] // pretty-expanded FIXME #23616 fn f(g: F) -> T where F: FnOnce() -> T { g() } diff --git a/tests/ui/never_type/diverging-fallback-unconstrained-return.rs b/tests/ui/never_type/diverging-fallback-unconstrained-return.rs index 7ea97126f89c..26c8175be638 100644 --- a/tests/ui/never_type/diverging-fallback-unconstrained-return.rs +++ b/tests/ui/never_type/diverging-fallback-unconstrained-return.rs @@ -1,4 +1,4 @@ -// Variant of diverging-falllback-control-flow that tests +// Variant of diverging-fallback-control-flow that tests // the specific case of a free function with an unconstrained // return type. This captures the pattern we saw in the wild // in the objc crate, where changing the fallback from `!` to `()` @@ -9,7 +9,7 @@ // revisions: nofallback fallback #![cfg_attr(fallback, feature(never_type, never_type_fallback))] - +#![allow(unit_bindings)] fn make_unit() {} From 244e181a5fa7ba3a63678b83625b71a4427a3a82 Mon Sep 17 00:00:00 2001 From: Qiu Chaofan Date: Tue, 21 Nov 2023 01:17:37 +0800 Subject: [PATCH 02/66] Enable profiler in dist-powerpc64-linux --- src/ci/docker/host-x86_64/dist-powerpc64-linux/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ci/docker/host-x86_64/dist-powerpc64-linux/Dockerfile b/src/ci/docker/host-x86_64/dist-powerpc64-linux/Dockerfile index c88185a2000d..298282a76463 100644 --- a/src/ci/docker/host-x86_64/dist-powerpc64-linux/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-powerpc64-linux/Dockerfile @@ -26,5 +26,5 @@ ENV \ ENV HOSTS=powerpc64-unknown-linux-gnu -ENV RUST_CONFIGURE_ARGS --enable-extended --disable-docs +ENV RUST_CONFIGURE_ARGS --enable-extended --enable-profiler --disable-docs ENV SCRIPT python3 ../x.py dist --host $HOSTS --target $HOSTS From 0000b35288f7f7d929dd9afe7a5f4b47305f8bff Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 20 Nov 2023 03:27:41 +0000 Subject: [PATCH 03/66] Document DefiningAnchor a bit more --- compiler/rustc_middle/src/traits/mod.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 6cd75e087276..8af4f57d5e83 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -956,13 +956,26 @@ pub enum CodegenObligationError { FulfillmentError, } +/// Defines the treatment of opaque types in a given inference context. +/// +/// This affects both what opaques are allowed to be defined, but also whether +/// opaques are replaced with inference vars eagerly in the old solver (e.g. +/// in projection, and in the signature during function type-checking). #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, HashStable, TypeFoldable, TypeVisitable)] pub enum DefiningAnchor { - /// `DefId` of the item. + /// Define opaques which are in-scope of the `LocalDefId`. Also, eagerly + /// replace opaque types in `replace_opaque_types_with_inference_vars`. Bind(LocalDefId), - /// When opaque types are not resolved, we `Bubble` up, meaning - /// return the opaque/hidden type pair from query, for caller of query to handle it. + /// In contexts where we don't currently know what opaques are allowed to be + /// defined, such as (old solver) canonical queries, we will simply allow + /// opaques to be defined, but "bubble" them up in the canonical response or + /// otherwise treat them to be handled later. + /// + /// We do not eagerly replace opaque types in `replace_opaque_types_with_inference_vars`, + /// which may affect what predicates pass and fail in the old trait solver. Bubble, - /// Used to catch type mismatch errors when handling opaque types. + /// Do not allow any opaques to be defined. This is used to catch type mismatch + /// errors when handling opaque types, and also should be used when we would + /// otherwise reveal opaques (such as [`Reveal::All`] reveal mode). Error, } From 273dc22b04411b9c156375d15ad2c8cead2e619e Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 20 Nov 2023 23:35:20 +0000 Subject: [PATCH 04/66] Don't ICE when ambiguity is found when selecting Index implementation in typeck --- compiler/rustc_hir_typeck/src/expr.rs | 22 +++++++++++--- .../bad-index-modulo-higher-ranked-regions.rs | 29 +++++++++++++++++++ ...-index-modulo-higher-ranked-regions.stderr | 9 ++++++ 3 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs create mode 100644 tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index d9b27fc13182..8fcbe90e91a8 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -3064,7 +3064,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return None; }; - self.commit_if_ok(|_| { + self.commit_if_ok(|snapshot| { + let outer_universe = self.universe(); + let ocx = ObligationCtxt::new(self); let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id); let impl_trait_ref = @@ -3074,7 +3076,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Match the impl self type against the base ty. If this fails, // we just skip this impl, since it's not particularly useful. let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref); - ocx.eq(&cause, self.param_env, impl_trait_ref.self_ty(), base_ty)?; + ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?; // Register the impl's predicates. One of these predicates // must be unsatisfied, or else we wouldn't have gotten here @@ -3110,11 +3112,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ty::new_projection(self.tcx, index_trait_output_def_id, impl_trait_ref.args), ); - let errors = ocx.select_where_possible(); + let true_errors = ocx.select_where_possible(); + + // Do a leak check -- we can't really report report a useful error here, + // but it at least avoids an ICE when the error has to do with higher-ranked + // lifetimes. + self.leak_check(outer_universe, Some(snapshot))?; + + // Bail if we have ambiguity errors, which we can't report in a useful way. + let ambiguity_errors = ocx.select_all_or_error(); + if true_errors.is_empty() && !ambiguity_errors.is_empty() { + return Err(NoSolution); + } + // There should be at least one error reported. If not, we // will still delay a span bug in `report_fulfillment_errors`. Ok::<_, NoSolution>(( - self.err_ctxt().report_fulfillment_errors(errors), + self.err_ctxt().report_fulfillment_errors(true_errors), impl_trait_ref.args.type_at(1), element_ty, )) diff --git a/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs new file mode 100644 index 000000000000..c8f6db7aef3e --- /dev/null +++ b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs @@ -0,0 +1,29 @@ +// Test against ICE in #118111 + +use std::ops::Index; + +struct Map { + f: F, + inner: T, +} + +impl Index for Map +where + T: Index, + F: FnOnce(&T, Idx) -> Idx, +{ + type Output = T::Output; + + fn index(&self, index: Idx) -> &Self::Output { + todo!() + } +} + +fn main() { + Map { inner: [0_usize], f: |_, i: usize| 1_usize }[0]; + //~^ ERROR cannot index into a value of type + // Problem here is that + // `f: |_, i: usize| ...` + // should be + // `f: |_: &_, i: usize| ...` +} diff --git a/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr new file mode 100644 index 000000000000..7c9784308391 --- /dev/null +++ b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr @@ -0,0 +1,9 @@ +error[E0608]: cannot index into a value of type `Map<[usize; 1], {closure@$DIR/bad-index-modulo-higher-ranked-regions.rs:23:32: 23:45}>` + --> $DIR/bad-index-modulo-higher-ranked-regions.rs:23:55 + | +LL | Map { inner: [0_usize], f: |_, i: usize| 1_usize }[0]; + | ^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0608`. From 018b85986d67945d50ea7aac176307877aaa053a Mon Sep 17 00:00:00 2001 From: ouz-a Date: Thu, 16 Nov 2023 16:04:26 +0300 Subject: [PATCH 05/66] Add VarDebugInfo to Stable MIR --- compiler/rustc_smir/src/rustc_smir/mod.rs | 45 +++++++++++++++++++- compiler/stable_mir/src/mir/body.rs | 50 +++++++++++++++++++++-- compiler/stable_mir/src/mir/visit.rs | 26 +++++++++++- 3 files changed, 116 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 167a01ab7990..e83e301d83bf 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -18,7 +18,10 @@ use rustc_middle::ty::{self, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, Variance use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_target::abi::FieldIdx; use stable_mir::mir::mono::InstanceDef; -use stable_mir::mir::{Body, CopyNonOverlapping, Statement, UserTypeProjection, VariantIdx}; +use stable_mir::mir::{ + Body, ConstOperand, CopyNonOverlapping, Statement, UserTypeProjection, VarDebugInfoFragment, + VariantIdx, +}; use stable_mir::ty::{ AdtDef, AdtKind, ClosureDef, ClosureKind, Const, ConstId, ConstantKind, EarlyParamRegion, FloatTy, FnDef, GenericArgs, GenericParamDef, IntTy, LineInfo, Movability, RigidTy, Span, @@ -444,10 +447,50 @@ impl<'tcx> Stable<'tcx> for mir::Body<'tcx> { }) .collect(), self.arg_count, + self.var_debug_info.iter().map(|info| info.stable(tables)).collect(), ) } } +impl<'tcx> Stable<'tcx> for mir::VarDebugInfo<'tcx> { + type T = stable_mir::mir::VarDebugInfo; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + stable_mir::mir::VarDebugInfo { + name: self.name.to_string(), + source_info: stable_mir::mir::SourceInfo { + span: self.source_info.span.stable(tables), + scope: self.source_info.scope.into(), + }, + composite: { + if let Some(composite) = &self.composite { + Some(VarDebugInfoFragment { + ty: composite.ty.stable(tables), + projection: composite.projection.iter().map(|e| e.stable(tables)).collect(), + }) + } else { + None + } + }, + value: { + match self.value { + mir::VarDebugInfoContents::Place(place) => { + stable_mir::mir::VarDebugInfoContents::Place(place.stable(tables)) + } + mir::VarDebugInfoContents::Const(const_operand) => { + let op = ConstOperand { + span: const_operand.span.stable(tables), + user_ty: const_operand.user_ty.map(|index| index.as_usize()), + const_: const_operand.const_.stable(tables), + }; + stable_mir::mir::VarDebugInfoContents::Const(op) + } + } + }, + argument_index: self.argument_index, + } + } +} + impl<'tcx> Stable<'tcx> for mir::Statement<'tcx> { type T = stable_mir::mir::Statement; fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs index ac07246dfd3e..8d237fc9f1d9 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -2,7 +2,7 @@ use crate::mir::pretty::{function_body, pretty_statement}; use crate::ty::{ AdtDef, ClosureDef, Const, CoroutineDef, GenericArgs, Movability, Region, RigidTy, Ty, TyKind, }; -use crate::{Error, Opaque, Span}; +use crate::{Error, Opaque, Span, Symbol}; use std::io; /// The SMIR representation of a single function. @@ -19,6 +19,9 @@ pub struct Body { // The number of arguments this function takes. pub(super) arg_count: usize, + + // Debug information pertaining to user variables, including captures. + pub(super) var_debug_info: Vec, } impl Body { @@ -26,14 +29,19 @@ impl Body { /// /// A constructor is required to build a `Body` from outside the crate /// because the `arg_count` and `locals` fields are private. - pub fn new(blocks: Vec, locals: LocalDecls, arg_count: usize) -> Self { + pub fn new( + blocks: Vec, + locals: LocalDecls, + arg_count: usize, + var_debug_info: Vec, + ) -> Self { // If locals doesn't contain enough entries, it can lead to panics in // `ret_local`, `arg_locals`, and `inner_locals`. assert!( locals.len() > arg_count, "A Body must contain at least a local for the return value and each of the function's arguments" ); - Self { blocks, locals, arg_count } + Self { blocks, locals, arg_count, var_debug_info } } /// Return local that holds this function's return value. @@ -427,6 +435,42 @@ pub struct Place { pub projection: Vec, } +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct VarDebugInfo { + pub name: Symbol, + pub source_info: SourceInfo, + pub composite: Option, + pub value: VarDebugInfoContents, + pub argument_index: Option, +} + +pub type SourceScope = u32; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SourceInfo { + pub span: Span, + pub scope: SourceScope, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct VarDebugInfoFragment { + pub ty: Ty, + pub projection: Vec, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum VarDebugInfoContents { + Place(Place), + Const(ConstOperand), +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ConstOperand { + pub span: Span, + pub user_ty: Option, + pub const_: Const, +} + // In MIR ProjectionElem is parameterized on the second Field argument and the Index argument. This // is so it can be used for both Places (for which the projection elements are of type // ProjectionElem) and user-provided type annotations (for which the projection elements diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs index 40bedd67352f..488363d6a7f1 100644 --- a/compiler/stable_mir/src/mir/visit.rs +++ b/compiler/stable_mir/src/mir/visit.rs @@ -128,8 +128,12 @@ pub trait MirVisitor { self.super_assert_msg(msg, location) } + fn visit_var_debug_info(&mut self, var_debug_info: &VarDebugInfo) { + self.super_var_debug_info(var_debug_info); + } + fn super_body(&mut self, body: &Body) { - let Body { blocks, locals: _, arg_count } = body; + let Body { blocks, locals: _, arg_count, var_debug_info } = body; for bb in blocks { self.visit_basic_block(bb); @@ -145,6 +149,10 @@ pub trait MirVisitor { for (idx, arg) in body.inner_locals().iter().enumerate() { self.visit_local_decl(idx + local_start, arg) } + + for info in var_debug_info.iter() { + self.visit_var_debug_info(info); + } } fn super_basic_block(&mut self, bb: &BasicBlock) { @@ -382,6 +390,22 @@ pub trait MirVisitor { let _ = args; } + fn super_var_debug_info(&mut self, var_debug_info: &VarDebugInfo) { + self.visit_span(&var_debug_info.source_info.span); + let location = Location(var_debug_info.source_info.span); + if let Some(composite) = &var_debug_info.composite { + self.visit_ty(&composite.ty, location); + } + match &var_debug_info.value { + VarDebugInfoContents::Place(place) => { + self.visit_place(place, PlaceContext::NON_USE, location); + } + VarDebugInfoContents::Const(constant) => { + self.visit_const(&constant.const_, location); + } + } + } + fn super_assert_msg(&mut self, msg: &AssertMessage, location: Location) { match msg { AssertMessage::BoundsCheck { len, index } => { From d0dd19a6c959c90eb7b28c3fa7f127b92fd0af36 Mon Sep 17 00:00:00 2001 From: ouz-a Date: Fri, 17 Nov 2023 23:41:34 +0300 Subject: [PATCH 06/66] de-structure variable and add stables --- compiler/rustc_smir/src/rustc_smir/mod.rs | 68 +++++++++++++---------- compiler/stable_mir/src/mir/visit.rs | 10 ++-- 2 files changed, 45 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index e83e301d83bf..04986a6c02fb 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -457,35 +457,9 @@ impl<'tcx> Stable<'tcx> for mir::VarDebugInfo<'tcx> { fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { stable_mir::mir::VarDebugInfo { name: self.name.to_string(), - source_info: stable_mir::mir::SourceInfo { - span: self.source_info.span.stable(tables), - scope: self.source_info.scope.into(), - }, - composite: { - if let Some(composite) = &self.composite { - Some(VarDebugInfoFragment { - ty: composite.ty.stable(tables), - projection: composite.projection.iter().map(|e| e.stable(tables)).collect(), - }) - } else { - None - } - }, - value: { - match self.value { - mir::VarDebugInfoContents::Place(place) => { - stable_mir::mir::VarDebugInfoContents::Place(place.stable(tables)) - } - mir::VarDebugInfoContents::Const(const_operand) => { - let op = ConstOperand { - span: const_operand.span.stable(tables), - user_ty: const_operand.user_ty.map(|index| index.as_usize()), - const_: const_operand.const_.stable(tables), - }; - stable_mir::mir::VarDebugInfoContents::Const(op) - } - } - }, + source_info: self.source_info.stable(tables), + composite: self.composite.as_ref().map(|composite| composite.stable(tables)), + value: self.value.stable(tables), argument_index: self.argument_index, } } @@ -498,6 +472,42 @@ impl<'tcx> Stable<'tcx> for mir::Statement<'tcx> { } } +impl<'tcx> Stable<'tcx> for mir::SourceInfo { + type T = stable_mir::mir::SourceInfo; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + stable_mir::mir::SourceInfo { span: self.span.stable(tables), scope: self.scope.into() } + } +} + +impl<'tcx> Stable<'tcx> for mir::VarDebugInfoFragment<'tcx> { + type T = stable_mir::mir::VarDebugInfoFragment; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + VarDebugInfoFragment { + ty: self.ty.stable(tables), + projection: self.projection.iter().map(|e| e.stable(tables)).collect(), + } + } +} + +impl<'tcx> Stable<'tcx> for mir::VarDebugInfoContents<'tcx> { + type T = stable_mir::mir::VarDebugInfoContents; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + match self { + mir::VarDebugInfoContents::Place(place) => { + stable_mir::mir::VarDebugInfoContents::Place(place.stable(tables)) + } + mir::VarDebugInfoContents::Const(const_operand) => { + let op = ConstOperand { + span: const_operand.span.stable(tables), + user_ty: const_operand.user_ty.map(|index| index.as_usize()), + const_: const_operand.const_.stable(tables), + }; + stable_mir::mir::VarDebugInfoContents::Const(op) + } + } + } +} + impl<'tcx> Stable<'tcx> for mir::StatementKind<'tcx> { type T = stable_mir::mir::StatementKind; fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs index 488363d6a7f1..d90808725ae4 100644 --- a/compiler/stable_mir/src/mir/visit.rs +++ b/compiler/stable_mir/src/mir/visit.rs @@ -391,12 +391,14 @@ pub trait MirVisitor { } fn super_var_debug_info(&mut self, var_debug_info: &VarDebugInfo) { - self.visit_span(&var_debug_info.source_info.span); - let location = Location(var_debug_info.source_info.span); - if let Some(composite) = &var_debug_info.composite { + let VarDebugInfo { source_info, composite, value, name: _, argument_index: _ } = + var_debug_info; + self.visit_span(&source_info.span); + let location = Location(source_info.span); + if let Some(composite) = composite { self.visit_ty(&composite.ty, location); } - match &var_debug_info.value { + match value { VarDebugInfoContents::Place(place) => { self.visit_place(place, PlaceContext::NON_USE, location); } From 0b25415559662352bbfd03a315d2a715663618b6 Mon Sep 17 00:00:00 2001 From: ouz-a Date: Tue, 21 Nov 2023 16:56:19 +0300 Subject: [PATCH 07/66] remove quotation from filename --- compiler/rustc_smir/src/rustc_smir/mod.rs | 16 +++++++--------- compiler/stable_mir/src/lib.rs | 2 +- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 167a01ab7990..0201df721f29 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -69,15 +69,13 @@ impl<'tcx> Context for TablesWrapper<'tcx> { fn get_filename(&self, span: &Span) -> Filename { let tables = self.0.borrow(); - opaque( - &tables - .tcx - .sess - .source_map() - .span_to_filename(tables[*span]) - .display(rustc_span::FileNameDisplayPreference::Local) - .to_string(), - ) + tables + .tcx + .sess + .source_map() + .span_to_filename(tables[*span]) + .display(rustc_span::FileNameDisplayPreference::Local) + .to_string() } fn get_lines(&self, span: &Span) -> LineInfo { diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs index 91f1066d7205..5eb6a8a5e543 100644 --- a/compiler/stable_mir/src/lib.rs +++ b/compiler/stable_mir/src/lib.rs @@ -110,7 +110,7 @@ pub enum ItemKind { Const, } -pub type Filename = Opaque; +pub type Filename = String; /// Holds information about an item in the crate. #[derive(Copy, Clone, PartialEq, Eq, Debug)] From 08803eb4c87b3b1895fae1d071229c1cf23b39d5 Mon Sep 17 00:00:00 2001 From: roblabla Date: Tue, 21 Nov 2023 16:33:19 +0100 Subject: [PATCH 08/66] Update backtrace submodule --- library/backtrace | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/backtrace b/library/backtrace index e9da96eb452a..6145fe6bac65 160000 --- a/library/backtrace +++ b/library/backtrace @@ -1 +1 @@ -Subproject commit e9da96eb452aa65e79e2342be700544afe509440 +Subproject commit 6145fe6bac65c38375f1216a565a6cc7deb89a2d From f26e8ff3ac2319b23bc23ba4154e2de49de98a1e Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 4 Nov 2023 16:49:20 +0000 Subject: [PATCH 09/66] Uplift BoundVar --- compiler/rustc_middle/src/ty/mod.rs | 2 +- compiler/rustc_middle/src/ty/sty.rs | 7 +------ compiler/rustc_type_ir/src/lib.rs | 7 +++++++ 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2436daf62cf2..78c8c1b588ee 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -94,7 +94,7 @@ pub use self::parameterized::ParameterizedOverTcx; pub use self::rvalue_scopes::RvalueScopes; pub use self::sty::BoundRegionKind::*; pub use self::sty::{ - AliasTy, Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, + AliasTy, Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig, ClauseKind, ClosureArgs, ClosureArgsParts, ConstKind, CoroutineArgs, CoroutineArgsParts, EarlyParamRegion, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig, GenSig, InlineConstArgs, diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index ea0e179c00de..9c5b5b69c825 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -32,6 +32,7 @@ use std::fmt; use std::ops::{ControlFlow, Deref, Range}; use ty::util::IntTypeExt; +use rustc_type_ir::BoundVar; use rustc_type_ir::ClauseKind as IrClauseKind; use rustc_type_ir::CollectAndApply; use rustc_type_ir::ConstKind as IrConstKind; @@ -1621,12 +1622,6 @@ impl Atom for RegionVid { } } -rustc_index::newtype_index! { - #[derive(HashStable)] - #[debug_format = "{}"] - pub struct BoundVar {} -} - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] #[derive(HashStable)] pub struct BoundTy { diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index acea7aa46f6f..d293a9341fe2 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -332,3 +332,10 @@ impl UniverseIndex { self.private < other.private } } + +rustc_index::newtype_index! { + #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] + #[debug_format = "{}"] + #[gate_rustc_only] + pub struct BoundVar {} +} From d1daf0e841ada63416c0affbe076e7000cf83367 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 4 Nov 2023 17:33:11 +0000 Subject: [PATCH 10/66] Uplift CanonicalVarInfo and friends --- compiler/rustc_middle/src/infer/canonical.rs | 157 +----------- compiler/rustc_middle/src/ty/mod.rs | 42 +++ compiler/rustc_type_ir/src/canonical.rs | 256 ++++++++++++++++++- compiler/rustc_type_ir/src/interner.rs | 16 +- 4 files changed, 313 insertions(+), 158 deletions(-) diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index 5a957d2c26d6..ef5a1caadb7b 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -23,6 +23,8 @@ use rustc_macros::HashStable; use rustc_type_ir::Canonical as IrCanonical; +use rustc_type_ir::CanonicalVarInfo as IrCanonicalVarInfo; +pub use rustc_type_ir::{CanonicalTyVarKind, CanonicalVarKind}; use smallvec::SmallVec; use std::ops::Index; @@ -33,6 +35,8 @@ use crate::ty::{self, BoundVar, List, Region, Ty, TyCtxt}; pub type Canonical<'tcx, V> = IrCanonical, V>; +pub type CanonicalVarInfo<'tcx> = IrCanonicalVarInfo>; + pub type CanonicalVarInfos<'tcx> = &'tcx List>; impl<'tcx> ty::TypeFoldable> for CanonicalVarInfos<'tcx> { @@ -138,158 +142,6 @@ impl<'tcx> Default for OriginalQueryValues<'tcx> { } } -/// Information about a canonical variable that is included with the -/// canonical value. This is sufficient information for code to create -/// a copy of the canonical value in some other inference context, -/// with fresh inference variables replacing the canonical values. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable, HashStable)] -#[derive(TypeFoldable, TypeVisitable)] -pub struct CanonicalVarInfo<'tcx> { - pub kind: CanonicalVarKind<'tcx>, -} - -impl<'tcx> CanonicalVarInfo<'tcx> { - pub fn universe(&self) -> ty::UniverseIndex { - self.kind.universe() - } - - #[must_use] - pub fn with_updated_universe(self, ui: ty::UniverseIndex) -> CanonicalVarInfo<'tcx> { - CanonicalVarInfo { kind: self.kind.with_updated_universe(ui) } - } - - pub fn is_existential(&self) -> bool { - match self.kind { - CanonicalVarKind::Ty(_) => true, - CanonicalVarKind::PlaceholderTy(_) => false, - CanonicalVarKind::Region(_) => true, - CanonicalVarKind::PlaceholderRegion(..) => false, - CanonicalVarKind::Const(..) => true, - CanonicalVarKind::PlaceholderConst(_, _) => false, - CanonicalVarKind::Effect => true, - } - } - - pub fn is_region(&self) -> bool { - match self.kind { - CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => true, - CanonicalVarKind::Ty(_) - | CanonicalVarKind::PlaceholderTy(_) - | CanonicalVarKind::Const(_, _) - | CanonicalVarKind::PlaceholderConst(_, _) - | CanonicalVarKind::Effect => false, - } - } - - pub fn expect_placeholder_index(self) -> usize { - match self.kind { - CanonicalVarKind::Ty(_) - | CanonicalVarKind::Region(_) - | CanonicalVarKind::Const(_, _) - | CanonicalVarKind::Effect => bug!("expected placeholder: {self:?}"), - - CanonicalVarKind::PlaceholderRegion(placeholder) => placeholder.bound.var.as_usize(), - CanonicalVarKind::PlaceholderTy(placeholder) => placeholder.bound.var.as_usize(), - CanonicalVarKind::PlaceholderConst(placeholder, _) => placeholder.bound.as_usize(), - } - } -} - -/// Describes the "kind" of the canonical variable. This is a "kind" -/// in the type-theory sense of the term -- i.e., a "meta" type system -/// that analyzes type-like values. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable, HashStable)] -#[derive(TypeFoldable, TypeVisitable)] -pub enum CanonicalVarKind<'tcx> { - /// Some kind of type inference variable. - Ty(CanonicalTyVarKind), - - /// A "placeholder" that represents "any type". - PlaceholderTy(ty::PlaceholderType), - - /// Region variable `'?R`. - Region(ty::UniverseIndex), - - /// A "placeholder" that represents "any region". Created when you - /// are solving a goal like `for<'a> T: Foo<'a>` to represent the - /// bound region `'a`. - PlaceholderRegion(ty::PlaceholderRegion), - - /// Some kind of const inference variable. - Const(ty::UniverseIndex, Ty<'tcx>), - - /// Effect variable `'?E`. - Effect, - - /// A "placeholder" that represents "any const". - PlaceholderConst(ty::PlaceholderConst, Ty<'tcx>), -} - -impl<'tcx> CanonicalVarKind<'tcx> { - pub fn universe(self) -> ty::UniverseIndex { - match self { - CanonicalVarKind::Ty(CanonicalTyVarKind::General(ui)) => ui, - CanonicalVarKind::Ty(CanonicalTyVarKind::Float | CanonicalTyVarKind::Int) => { - ty::UniverseIndex::ROOT - } - CanonicalVarKind::Effect => ty::UniverseIndex::ROOT, - CanonicalVarKind::PlaceholderTy(placeholder) => placeholder.universe, - CanonicalVarKind::Region(ui) => ui, - CanonicalVarKind::PlaceholderRegion(placeholder) => placeholder.universe, - CanonicalVarKind::Const(ui, _) => ui, - CanonicalVarKind::PlaceholderConst(placeholder, _) => placeholder.universe, - } - } - - /// Replaces the universe of this canonical variable with `ui`. - /// - /// In case this is a float or int variable, this causes an ICE if - /// the updated universe is not the root. - pub fn with_updated_universe(self, ui: ty::UniverseIndex) -> CanonicalVarKind<'tcx> { - match self { - CanonicalVarKind::Ty(CanonicalTyVarKind::General(_)) => { - CanonicalVarKind::Ty(CanonicalTyVarKind::General(ui)) - } - CanonicalVarKind::Ty(CanonicalTyVarKind::Int | CanonicalTyVarKind::Float) - | CanonicalVarKind::Effect => { - assert_eq!(ui, ty::UniverseIndex::ROOT); - self - } - CanonicalVarKind::PlaceholderTy(placeholder) => { - CanonicalVarKind::PlaceholderTy(ty::Placeholder { universe: ui, ..placeholder }) - } - CanonicalVarKind::Region(_) => CanonicalVarKind::Region(ui), - CanonicalVarKind::PlaceholderRegion(placeholder) => { - CanonicalVarKind::PlaceholderRegion(ty::Placeholder { universe: ui, ..placeholder }) - } - CanonicalVarKind::Const(_, ty) => CanonicalVarKind::Const(ui, ty), - CanonicalVarKind::PlaceholderConst(placeholder, ty) => { - CanonicalVarKind::PlaceholderConst( - ty::Placeholder { universe: ui, ..placeholder }, - ty, - ) - } - } - } -} - -/// Rust actually has more than one category of type variables; -/// notably, the type variables we create for literals (e.g., 22 or -/// 22.) can only be instantiated with integral/float types (e.g., -/// usize or f32). In order to faithfully reproduce a type, we need to -/// know what set of types a given type variable can be unified with. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable, HashStable)] -pub enum CanonicalTyVarKind { - /// General type variable `?T` that can be unified with arbitrary types. - General(ty::UniverseIndex), - - /// Integral type variable `?I` (that can only be unified with integral types). - Int, - - /// Floating-point type variable `?F` (that can only be unified with float types). - Float, -} - /// After we execute a query with a canonicalized key, we get back a /// `Canonical>`. You can use /// `instantiate_query_result` to access the data in this result. @@ -366,7 +218,6 @@ pub type QueryOutlivesConstraint<'tcx> = TrivialTypeTraversalImpls! { crate::infer::canonical::Certainty, - crate::infer::canonical::CanonicalTyVarKind, } impl<'tcx> CanonicalVarValues<'tcx> { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 78c8c1b588ee..c9264b2135f9 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1517,8 +1517,36 @@ pub struct Placeholder { pub type PlaceholderRegion = Placeholder; +impl rustc_type_ir::Placeholder for PlaceholderRegion { + fn universe(&self) -> UniverseIndex { + self.universe + } + + fn var(&self) -> BoundVar { + self.bound.var + } + + fn with_updated_universe(self, ui: UniverseIndex) -> Self { + Placeholder { universe: ui, ..self } + } +} + pub type PlaceholderType = Placeholder; +impl rustc_type_ir::Placeholder for PlaceholderType { + fn universe(&self) -> UniverseIndex { + self.universe + } + + fn var(&self) -> BoundVar { + self.bound.var + } + + fn with_updated_universe(self, ui: UniverseIndex) -> Self { + Placeholder { universe: ui, ..self } + } +} + #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)] #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)] pub struct BoundConst<'tcx> { @@ -1528,6 +1556,20 @@ pub struct BoundConst<'tcx> { pub type PlaceholderConst = Placeholder; +impl rustc_type_ir::Placeholder for PlaceholderConst { + fn universe(&self) -> UniverseIndex { + self.universe + } + + fn var(&self) -> BoundVar { + self.bound + } + + fn with_updated_universe(self, ui: UniverseIndex) -> Self { + Placeholder { universe: ui, ..self } + } +} + /// When type checking, we use the `ParamEnv` to track /// details about the set of where-clauses that are in scope at this /// particular point. diff --git a/compiler/rustc_type_ir/src/canonical.rs b/compiler/rustc_type_ir/src/canonical.rs index 9f170c5b4db6..d2768703297e 100644 --- a/compiler/rustc_type_ir/src/canonical.rs +++ b/compiler/rustc_type_ir/src/canonical.rs @@ -4,7 +4,7 @@ use std::ops::ControlFlow; use crate::fold::{FallibleTypeFolder, TypeFoldable}; use crate::visit::{TypeVisitable, TypeVisitor}; -use crate::{Interner, UniverseIndex}; +use crate::{Interner, Placeholder, UniverseIndex}; /// A "canonicalized" type `V` is one where all free inference /// variables have been rewritten to "canonical vars". These are @@ -113,3 +113,257 @@ where self.variables.visit_with(folder) } } + +/// Information about a canonical variable that is included with the +/// canonical value. This is sufficient information for code to create +/// a copy of the canonical value in some other inference context, +/// with fresh inference variables replacing the canonical values. +#[derive(derivative::Derivative)] +#[derivative( + Clone(bound = ""), + Hash(bound = ""), + Copy(bound = "CanonicalVarKind: Copy"), + Debug(bound = "") +)] +#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +pub struct CanonicalVarInfo { + pub kind: CanonicalVarKind, +} + +impl PartialEq for CanonicalVarInfo { + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + } +} + +impl Eq for CanonicalVarInfo {} + +impl TypeVisitable for CanonicalVarInfo +where + I::Ty: TypeVisitable, +{ + fn visit_with>(&self, visitor: &mut V) -> ControlFlow { + self.kind.visit_with(visitor) + } +} + +impl TypeFoldable for CanonicalVarInfo +where + I::Ty: TypeFoldable, +{ + fn try_fold_with>(self, folder: &mut F) -> Result { + Ok(CanonicalVarInfo { kind: self.kind.try_fold_with(folder)? }) + } +} + +impl CanonicalVarInfo { + pub fn universe(&self) -> UniverseIndex { + self.kind.universe() + } + + #[must_use] + pub fn with_updated_universe(self, ui: UniverseIndex) -> CanonicalVarInfo { + CanonicalVarInfo { kind: self.kind.with_updated_universe(ui) } + } + + pub fn is_existential(&self) -> bool { + match self.kind { + CanonicalVarKind::Ty(_) => true, + CanonicalVarKind::PlaceholderTy(_) => false, + CanonicalVarKind::Region(_) => true, + CanonicalVarKind::PlaceholderRegion(..) => false, + CanonicalVarKind::Const(..) => true, + CanonicalVarKind::PlaceholderConst(_, _) => false, + CanonicalVarKind::Effect => true, + } + } + + pub fn is_region(&self) -> bool { + match self.kind { + CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => true, + CanonicalVarKind::Ty(_) + | CanonicalVarKind::PlaceholderTy(_) + | CanonicalVarKind::Const(_, _) + | CanonicalVarKind::PlaceholderConst(_, _) + | CanonicalVarKind::Effect => false, + } + } + + pub fn expect_placeholder_index(self) -> usize { + match self.kind { + CanonicalVarKind::Ty(_) + | CanonicalVarKind::Region(_) + | CanonicalVarKind::Const(_, _) + | CanonicalVarKind::Effect => panic!("expected placeholder: {self:?}"), + + CanonicalVarKind::PlaceholderRegion(placeholder) => placeholder.var().as_usize(), + CanonicalVarKind::PlaceholderTy(placeholder) => placeholder.var().as_usize(), + CanonicalVarKind::PlaceholderConst(placeholder, _) => placeholder.var().as_usize(), + } + } +} + +/// Describes the "kind" of the canonical variable. This is a "kind" +/// in the type-theory sense of the term -- i.e., a "meta" type system +/// that analyzes type-like values. +#[derive(derivative::Derivative)] +#[derivative(Clone(bound = ""), Hash(bound = ""), Debug(bound = ""))] +#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +pub enum CanonicalVarKind { + /// Some kind of type inference variable. + Ty(CanonicalTyVarKind), + + /// A "placeholder" that represents "any type". + PlaceholderTy(I::PlaceholderTy), + + /// Region variable `'?R`. + Region(UniverseIndex), + + /// A "placeholder" that represents "any region". Created when you + /// are solving a goal like `for<'a> T: Foo<'a>` to represent the + /// bound region `'a`. + PlaceholderRegion(I::PlaceholderRegion), + + /// Some kind of const inference variable. + Const(UniverseIndex, I::Ty), + + /// Effect variable `'?E`. + Effect, + + /// A "placeholder" that represents "any const". + PlaceholderConst(I::PlaceholderConst, I::Ty), +} + +impl Copy for CanonicalVarKind +where + I::PlaceholderTy: Copy, + I::PlaceholderRegion: Copy, + I::PlaceholderConst: Copy, + I::Ty: Copy, +{ +} + +impl PartialEq for CanonicalVarKind { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Ty(l0), Self::Ty(r0)) => l0 == r0, + (Self::PlaceholderTy(l0), Self::PlaceholderTy(r0)) => l0 == r0, + (Self::Region(l0), Self::Region(r0)) => l0 == r0, + (Self::PlaceholderRegion(l0), Self::PlaceholderRegion(r0)) => l0 == r0, + (Self::Const(l0, l1), Self::Const(r0, r1)) => l0 == r0 && l1 == r1, + (Self::PlaceholderConst(l0, l1), Self::PlaceholderConst(r0, r1)) => { + l0 == r0 && l1 == r1 + } + _ => std::mem::discriminant(self) == std::mem::discriminant(other), + } + } +} + +impl Eq for CanonicalVarKind {} + +impl TypeVisitable for CanonicalVarKind +where + I::Ty: TypeVisitable, +{ + fn visit_with>(&self, visitor: &mut V) -> ControlFlow { + match self { + CanonicalVarKind::Ty(_) + | CanonicalVarKind::PlaceholderTy(_) + | CanonicalVarKind::Region(_) + | CanonicalVarKind::PlaceholderRegion(_) + | CanonicalVarKind::Effect => ControlFlow::Continue(()), + CanonicalVarKind::Const(_, ty) | CanonicalVarKind::PlaceholderConst(_, ty) => { + ty.visit_with(visitor) + } + } + } +} + +impl TypeFoldable for CanonicalVarKind +where + I::Ty: TypeFoldable, +{ + fn try_fold_with>(self, folder: &mut F) -> Result { + Ok(match self { + CanonicalVarKind::Ty(kind) => CanonicalVarKind::Ty(kind), + CanonicalVarKind::Region(kind) => CanonicalVarKind::Region(kind), + CanonicalVarKind::Const(kind, ty) => { + CanonicalVarKind::Const(kind, ty.try_fold_with(folder)?) + } + CanonicalVarKind::PlaceholderTy(placeholder) => { + CanonicalVarKind::PlaceholderTy(placeholder) + } + CanonicalVarKind::PlaceholderRegion(placeholder) => { + CanonicalVarKind::PlaceholderRegion(placeholder) + } + CanonicalVarKind::PlaceholderConst(placeholder, ty) => { + CanonicalVarKind::PlaceholderConst(placeholder, ty.try_fold_with(folder)?) + } + CanonicalVarKind::Effect => CanonicalVarKind::Effect, + }) + } +} + +impl CanonicalVarKind { + pub fn universe(&self) -> UniverseIndex { + match self { + CanonicalVarKind::Ty(CanonicalTyVarKind::General(ui)) => *ui, + CanonicalVarKind::Region(ui) => *ui, + CanonicalVarKind::Const(ui, _) => *ui, + CanonicalVarKind::PlaceholderTy(placeholder) => placeholder.universe(), + CanonicalVarKind::PlaceholderRegion(placeholder) => placeholder.universe(), + CanonicalVarKind::PlaceholderConst(placeholder, _) => placeholder.universe(), + CanonicalVarKind::Ty(CanonicalTyVarKind::Float | CanonicalTyVarKind::Int) => { + UniverseIndex::ROOT + } + CanonicalVarKind::Effect => UniverseIndex::ROOT, + } + } + + /// Replaces the universe of this canonical variable with `ui`. + /// + /// In case this is a float or int variable, this causes an ICE if + /// the updated universe is not the root. + pub fn with_updated_universe(self, ui: UniverseIndex) -> CanonicalVarKind { + match self { + CanonicalVarKind::Ty(CanonicalTyVarKind::General(_)) => { + CanonicalVarKind::Ty(CanonicalTyVarKind::General(ui)) + } + CanonicalVarKind::Region(_) => CanonicalVarKind::Region(ui), + CanonicalVarKind::Const(_, ty) => CanonicalVarKind::Const(ui, ty), + + CanonicalVarKind::PlaceholderTy(placeholder) => { + CanonicalVarKind::PlaceholderTy(placeholder.with_updated_universe(ui)) + } + CanonicalVarKind::PlaceholderRegion(placeholder) => { + CanonicalVarKind::PlaceholderRegion(placeholder.with_updated_universe(ui)) + } + CanonicalVarKind::PlaceholderConst(placeholder, ty) => { + CanonicalVarKind::PlaceholderConst(placeholder.with_updated_universe(ui), ty) + } + CanonicalVarKind::Ty(CanonicalTyVarKind::Int | CanonicalTyVarKind::Float) + | CanonicalVarKind::Effect => { + assert_eq!(ui, UniverseIndex::ROOT); + self + } + } + } +} + +/// Rust actually has more than one category of type variables; +/// notably, the type variables we create for literals (e.g., 22 or +/// 22.) can only be instantiated with integral/float types (e.g., +/// usize or f32). In order to faithfully reproduce a type, we need to +/// know what set of types a given type variable can be unified with. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +pub enum CanonicalTyVarKind { + /// General type variable `?T` that can be unified with arbitrary types. + General(UniverseIndex), + + /// Integral type variable `?I` (that can only be unified with integral types). + Int, + + /// Floating-point type variable `?F` (that can only be unified with float types). + Float, +} diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 170a791fb54d..16508c1a2579 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -2,7 +2,7 @@ use smallvec::SmallVec; use std::fmt::Debug; use std::hash::Hash; -use crate::{DebugWithInfcx, Mutability}; +use crate::{BoundVar, DebugWithInfcx, Mutability, UniverseIndex}; pub trait Interner: Sized { type DefId: Clone + Debug + Hash + Ord; @@ -26,7 +26,7 @@ pub trait Interner: Sized { type AliasTy: Clone + DebugWithInfcx + Hash + Ord; type ParamTy: Clone + Debug + Hash + Ord; type BoundTy: Clone + Debug + Hash + Ord; - type PlaceholderTy: Clone + Debug + Hash + Ord; + type PlaceholderTy: Clone + Debug + Hash + Ord + Placeholder; // Things stored inside of tys type ErrorGuaranteed: Clone + Debug + Hash + Ord; @@ -37,7 +37,7 @@ pub trait Interner: Sized { // Kinds of consts type Const: Clone + DebugWithInfcx + Hash + Ord; type AliasConst: Clone + DebugWithInfcx + Hash + Ord; - type PlaceholderConst: Clone + Debug + Hash + Ord; + type PlaceholderConst: Clone + Debug + Hash + Ord + Placeholder; type ParamConst: Clone + Debug + Hash + Ord; type BoundConst: Clone + Debug + Hash + Ord; type ValueConst: Clone + Debug + Hash + Ord; @@ -49,7 +49,7 @@ pub trait Interner: Sized { type BoundRegion: Clone + Debug + Hash + Ord; type LateParamRegion: Clone + Debug + Hash + Ord; type InferRegion: Clone + DebugWithInfcx + Hash + Ord; - type PlaceholderRegion: Clone + Debug + Hash + Ord; + type PlaceholderRegion: Clone + Debug + Hash + Ord + Placeholder; // Predicates type Predicate: Clone + Debug + Hash + Eq; @@ -64,6 +64,14 @@ pub trait Interner: Sized { fn ty_and_mut_to_parts(ty_and_mut: Self::TypeAndMut) -> (Self::Ty, Mutability); } +/// Common capabilities of placeholder kinds +pub trait Placeholder { + fn universe(&self) -> UniverseIndex; + fn var(&self) -> BoundVar; + + fn with_updated_universe(self, ui: UniverseIndex) -> Self; +} + /// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter` /// that produces `T` items. You could combine them with /// `f(&iter.collect::>())`, but this requires allocating memory for the From 9f15acec474dafe50617aa1623c987e3b6354246 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 19 Nov 2023 20:43:50 +0100 Subject: [PATCH 11/66] Remove `feature` from the list of well known check-cfg name --- compiler/rustc_session/src/config.rs | 3 +-- tests/ui/check-cfg/allow-same-level.stderr | 2 +- tests/ui/check-cfg/compact-names.stderr | 2 +- .../exhaustive-names-values.empty_cfg.stderr | 16 ++++++++++++++-- ...ustive-names-values.empty_names_values.stderr | 16 ++++++++++++++-- tests/ui/check-cfg/exhaustive-names-values.rs | 8 ++++++-- .../exhaustive-names.empty_names.stderr | 2 +- .../exhaustive-names.exhaustive_names.stderr | 2 +- tests/ui/check-cfg/stmt-no-ice.stderr | 2 +- tests/ui/check-cfg/well-known-names.rs | 1 + tests/ui/check-cfg/well-known-names.stderr | 16 +++++++++++----- 11 files changed, 52 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index d4f9122e7e38..e288a43c0e0a 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1443,9 +1443,8 @@ impl CheckCfg { let relocation_model_values = RelocModel::all(); // Unknown possible values: - // - `feature` // - `target_feature` - for name in [sym::feature, sym::target_feature] { + for name in [sym::target_feature] { self.expecteds.entry(name).or_insert(ExpectedValues::Any); } diff --git a/tests/ui/check-cfg/allow-same-level.stderr b/tests/ui/check-cfg/allow-same-level.stderr index b0c459fabf8e..19d9443d477a 100644 --- a/tests/ui/check-cfg/allow-same-level.stderr +++ b/tests/ui/check-cfg/allow-same-level.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `FALSE` LL | #[cfg(FALSE)] | ^^^^^ | - = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = note: `#[warn(unexpected_cfgs)]` on by default warning: 1 warning emitted diff --git a/tests/ui/check-cfg/compact-names.stderr b/tests/ui/check-cfg/compact-names.stderr index b0228774b751..ffde972a25ef 100644 --- a/tests/ui/check-cfg/compact-names.stderr +++ b/tests/ui/check-cfg/compact-names.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `target_architecture` LL | #[cfg(target(os = "linux", architecture = "arm"))] | ^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = note: `#[warn(unexpected_cfgs)]` on by default warning: 1 warning emitted diff --git a/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr b/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr index 12a055d02a7b..971abb1a21a4 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `value` @@ -17,5 +17,17 @@ LL | #[cfg(test = "value")] | = note: no expected value for `test` -warning: 2 warnings emitted +warning: unexpected `cfg` condition name: `feature` + --> $DIR/exhaustive-names-values.rs:19:7 + | +LL | #[cfg(feature = "unk")] + | ^^^^^^^^^^^^^^^ + +warning: unexpected `cfg` condition name: `feature` + --> $DIR/exhaustive-names-values.rs:26:7 + | +LL | #[cfg(feature = "std")] + | ^^^^^^^^^^^^^^^ + +warning: 4 warnings emitted diff --git a/tests/ui/check-cfg/exhaustive-names-values.empty_names_values.stderr b/tests/ui/check-cfg/exhaustive-names-values.empty_names_values.stderr index 12a055d02a7b..971abb1a21a4 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.empty_names_values.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.empty_names_values.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `value` @@ -17,5 +17,17 @@ LL | #[cfg(test = "value")] | = note: no expected value for `test` -warning: 2 warnings emitted +warning: unexpected `cfg` condition name: `feature` + --> $DIR/exhaustive-names-values.rs:19:7 + | +LL | #[cfg(feature = "unk")] + | ^^^^^^^^^^^^^^^ + +warning: unexpected `cfg` condition name: `feature` + --> $DIR/exhaustive-names-values.rs:26:7 + | +LL | #[cfg(feature = "std")] + | ^^^^^^^^^^^^^^^ + +warning: 4 warnings emitted diff --git a/tests/ui/check-cfg/exhaustive-names-values.rs b/tests/ui/check-cfg/exhaustive-names-values.rs index ef1e458b2498..ceb4831e22d3 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.rs +++ b/tests/ui/check-cfg/exhaustive-names-values.rs @@ -17,11 +17,15 @@ pub fn f() {} pub fn f() {} #[cfg(feature = "unk")] -//[feature]~^ WARNING unexpected `cfg` condition value -//[full]~^^ WARNING unexpected `cfg` condition value +//[empty_names_values]~^ WARNING unexpected `cfg` condition name +//[empty_cfg]~^^ WARNING unexpected `cfg` condition name +//[feature]~^^^ WARNING unexpected `cfg` condition value +//[full]~^^^^ WARNING unexpected `cfg` condition value pub fn feat() {} #[cfg(feature = "std")] +//[empty_names_values]~^ WARNING unexpected `cfg` condition name +//[empty_cfg]~^^ WARNING unexpected `cfg` condition name pub fn feat() {} #[cfg(windows)] diff --git a/tests/ui/check-cfg/exhaustive-names.empty_names.stderr b/tests/ui/check-cfg/exhaustive-names.empty_names.stderr index 6bc7845c8328..7d01c73cc09b 100644 --- a/tests/ui/check-cfg/exhaustive-names.empty_names.stderr +++ b/tests/ui/check-cfg/exhaustive-names.empty_names.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = note: `#[warn(unexpected_cfgs)]` on by default warning: 1 warning emitted diff --git a/tests/ui/check-cfg/exhaustive-names.exhaustive_names.stderr b/tests/ui/check-cfg/exhaustive-names.exhaustive_names.stderr index 6bc7845c8328..7d01c73cc09b 100644 --- a/tests/ui/check-cfg/exhaustive-names.exhaustive_names.stderr +++ b/tests/ui/check-cfg/exhaustive-names.exhaustive_names.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = note: `#[warn(unexpected_cfgs)]` on by default warning: 1 warning emitted diff --git a/tests/ui/check-cfg/stmt-no-ice.stderr b/tests/ui/check-cfg/stmt-no-ice.stderr index 900ea4e4da06..3fb3ae27ec48 100644 --- a/tests/ui/check-cfg/stmt-no-ice.stderr +++ b/tests/ui/check-cfg/stmt-no-ice.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `crossbeam_loom` LL | #[cfg(crossbeam_loom)] | ^^^^^^^^^^^^^^ | - = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = note: `#[warn(unexpected_cfgs)]` on by default warning: 1 warning emitted diff --git a/tests/ui/check-cfg/well-known-names.rs b/tests/ui/check-cfg/well-known-names.rs index 1dcb419b4a73..32c14703d25b 100644 --- a/tests/ui/check-cfg/well-known-names.rs +++ b/tests/ui/check-cfg/well-known-names.rs @@ -15,6 +15,7 @@ fn target_os() {} fn feature_misspell() {} #[cfg(feature = "foo")] +//~^ WARNING unexpected `cfg` condition name fn feature() {} #[cfg(uniw)] diff --git a/tests/ui/check-cfg/well-known-names.stderr b/tests/ui/check-cfg/well-known-names.stderr index 3001289b7e06..a986e61bcdc3 100644 --- a/tests/ui/check-cfg/well-known-names.stderr +++ b/tests/ui/check-cfg/well-known-names.stderr @@ -14,15 +14,21 @@ warning: unexpected `cfg` condition name: `features` --> $DIR/well-known-names.rs:13:7 | LL | #[cfg(features = "foo")] - | --------^^^^^^^^ - | | - | help: there is a config with a similar name: `feature` + | ^^^^^^^^^^^^^^^^ + | + = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` + +warning: unexpected `cfg` condition name: `feature` + --> $DIR/well-known-names.rs:17:7 + | +LL | #[cfg(feature = "foo")] + | ^^^^^^^^^^^^^^^ warning: unexpected `cfg` condition name: `uniw` - --> $DIR/well-known-names.rs:20:7 + --> $DIR/well-known-names.rs:21:7 | LL | #[cfg(uniw)] | ^^^^ help: there is a config with a similar name: `unix` -warning: 3 warnings emitted +warning: 4 warnings emitted From 1c37997fa70129efea84c02cf4d863a44660ab2e Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 19 Nov 2023 21:41:55 +0100 Subject: [PATCH 12/66] Improve diagnostic for unexpected feature config name from Cargo --- compiler/rustc_lint/src/context.rs | 2 ++ tests/ui/check-cfg/cargo-feature.rs | 14 ++++++++++++++ tests/ui/check-cfg/cargo-feature.stderr | 11 +++++++++++ 3 files changed, 27 insertions(+) create mode 100644 tests/ui/check-cfg/cargo-feature.rs create mode 100644 tests/ui/check-cfg/cargo-feature.stderr diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index d500c3b66d66..ad2047c1903e 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -739,6 +739,8 @@ pub trait LintContext { } else { db.span_suggestion(name_span, "there is a config with a similar name", best_match, Applicability::MaybeIncorrect); } + } else if name == sym::feature && std::env::var_os("CARGO").is_some() { + db.help("consider defining some features in `Cargo.toml`"); } else if !possibilities.is_empty() { let mut possibilities = possibilities.iter() .map(Symbol::as_str) diff --git a/tests/ui/check-cfg/cargo-feature.rs b/tests/ui/check-cfg/cargo-feature.rs new file mode 100644 index 000000000000..ea48c6ea2015 --- /dev/null +++ b/tests/ui/check-cfg/cargo-feature.rs @@ -0,0 +1,14 @@ +// This test checks that when no features are passed by Cargo we +// suggest adding some in the Cargo.toml instead of vomitting a +// list of all the expected names +// +// check-pass +// rustc-env:CARGO=/usr/bin/cargo +// compile-flags: --check-cfg=cfg() -Z unstable-options +// error-pattern:Cargo.toml + +#[cfg(feature = "serde")] +//~^ WARNING unexpected `cfg` condition name +fn ser() {} + +fn main() {} diff --git a/tests/ui/check-cfg/cargo-feature.stderr b/tests/ui/check-cfg/cargo-feature.stderr new file mode 100644 index 000000000000..619410a28f37 --- /dev/null +++ b/tests/ui/check-cfg/cargo-feature.stderr @@ -0,0 +1,11 @@ +warning: unexpected `cfg` condition name: `feature` + --> $DIR/cargo-feature.rs:10:7 + | +LL | #[cfg(feature = "serde")] + | ^^^^^^^^^^^^^^^^^ + | + = help: consider defining some features in `Cargo.toml` + = note: `#[warn(unexpected_cfgs)]` on by default + +warning: 1 warning emitted + From 54c122ec0d45799e795f8b2aca38227ce9b05fa5 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 19 Nov 2023 23:17:27 +0100 Subject: [PATCH 13/66] [Miri] Do not respect RUSTC_HOST_FLAGS since RUSTFLAGS isn't When building the standard library with Miri, it appears that cargo-miri does not respect the RUSTFLAGS and even if they did it would be wrong since they are created for ToolRustc not Std. To avoid errors ignore RUSTC_HOST_FLAGS for Miri. --- src/bootstrap/src/bin/rustc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/src/bin/rustc.rs b/src/bootstrap/src/bin/rustc.rs index 070a2da6afb8..af66cb3ffd7c 100644 --- a/src/bootstrap/src/bin/rustc.rs +++ b/src/bootstrap/src/bin/rustc.rs @@ -114,7 +114,7 @@ fn main() { { cmd.arg("-Ztls-model=initial-exec"); } - } else { + } else if std::env::var("MIRI").is_err() { // Find any host flags that were passed by bootstrap. // The flags are stored in a RUSTC_HOST_FLAGS variable, separated by spaces. if let Ok(flags) = std::env::var("RUSTC_HOST_FLAGS") { From 93298ee0dd938c0fece0ee5dbafe851e54dd6386 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 21 Nov 2023 04:02:46 +0000 Subject: [PATCH 14/66] Remove ClosureKind predicate kind --- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 1 - compiler/rustc_infer/src/traits/util.rs | 3 -- compiler/rustc_middle/src/ty/flags.rs | 3 -- compiler/rustc_middle/src/ty/mod.rs | 4 -- compiler/rustc_middle/src/ty/print/pretty.rs | 5 -- compiler/rustc_smir/src/rustc_smir/mod.rs | 7 --- .../src/solve/eval_ctxt/mod.rs | 2 - .../src/solve/fulfill.rs | 1 - .../src/traits/auto_trait.rs | 1 - .../error_reporting/type_err_ctxt_ext.rs | 5 -- .../src/traits/fulfill.rs | 14 ------ .../query/type_op/implied_outlives_bounds.rs | 1 - .../src/traits/select/candidate_assembly.rs | 7 ++- .../src/traits/select/confirmation.rs | 12 +---- .../src/traits/select/mod.rs | 13 ----- .../src/normalize_erasing_regions.rs | 1 - compiler/rustc_type_ir/src/predicate_kind.rs | 24 ---------- compiler/stable_mir/src/ty.rs | 1 - .../closure_context/issue-26046-fn-mut.stderr | 16 +++---- .../issue-26046-fn-once.stderr | 16 +++---- .../closure-origin-array-diagnostics.stderr | 16 +++---- .../closure-origin-tuple-diagnostics.stderr | 16 +++---- tests/ui/closures/closure-wrong-kind.stderr | 14 +++--- tests/ui/issues/issue-34349.stderr | 16 +++---- .../move-ref-patterns-closure-captures.stderr | 47 ++++++++----------- ...-infer-fn-once-move-from-projection.stderr | 15 +++--- 26 files changed, 73 insertions(+), 188 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 750ed2c34913..91540e0c284a 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -662,7 +662,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // this closure yet; this is exactly why the other // code is looking for a self type of an unresolved // inference variable. - | ty::PredicateKind::ClosureKind(..) | ty::PredicateKind::Ambiguous => None, }, diff --git a/compiler/rustc_infer/src/traits/util.rs b/compiler/rustc_infer/src/traits/util.rs index ed3409149d09..1bcae736fd95 100644 --- a/compiler/rustc_infer/src/traits/util.rs +++ b/compiler/rustc_infer/src/traits/util.rs @@ -308,9 +308,6 @@ impl<'tcx, O: Elaboratable<'tcx>> Elaborator<'tcx, O> { ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => { // Nothing to elaborate in a projection predicate. } - ty::PredicateKind::ClosureKind(..) => { - // Nothing to elaborate when waiting for a closure's kind to be inferred. - } ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) => { // Currently, we do not elaborate const-evaluatable // predicates. diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index 4d7b12662c66..cd9b429ec56c 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -263,9 +263,6 @@ impl FlagComputation { self.add_args(slice::from_ref(&arg)); } ty::PredicateKind::ObjectSafe(_def_id) => {} - ty::PredicateKind::ClosureKind(_def_id, args, _kind) => { - self.add_args(args); - } ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => { self.add_const(uv); } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2436daf62cf2..bab79bfcae9f 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -548,7 +548,6 @@ impl<'tcx> Predicate<'tcx> { | PredicateKind::Clause(ClauseKind::ConstArgHasType(..)) | PredicateKind::AliasRelate(..) | PredicateKind::ObjectSafe(_) - | PredicateKind::ClosureKind(_, _, _) | PredicateKind::Subtype(_) | PredicateKind::Coerce(_) | PredicateKind::Clause(ClauseKind::ConstEvaluatable(_)) @@ -1276,7 +1275,6 @@ impl<'tcx> Predicate<'tcx> { | PredicateKind::Clause(ClauseKind::RegionOutlives(..)) | PredicateKind::Clause(ClauseKind::WellFormed(..)) | PredicateKind::ObjectSafe(..) - | PredicateKind::ClosureKind(..) | PredicateKind::Clause(ClauseKind::TypeOutlives(..)) | PredicateKind::Clause(ClauseKind::ConstEvaluatable(..)) | PredicateKind::ConstEquate(..) @@ -1296,7 +1294,6 @@ impl<'tcx> Predicate<'tcx> { | PredicateKind::Clause(ClauseKind::RegionOutlives(..)) | PredicateKind::Clause(ClauseKind::WellFormed(..)) | PredicateKind::ObjectSafe(..) - | PredicateKind::ClosureKind(..) | PredicateKind::Clause(ClauseKind::TypeOutlives(..)) | PredicateKind::Clause(ClauseKind::ConstEvaluatable(..)) | PredicateKind::ConstEquate(..) @@ -1317,7 +1314,6 @@ impl<'tcx> Predicate<'tcx> { | PredicateKind::Clause(ClauseKind::RegionOutlives(..)) | PredicateKind::Clause(ClauseKind::WellFormed(..)) | PredicateKind::ObjectSafe(..) - | PredicateKind::ClosureKind(..) | PredicateKind::Clause(ClauseKind::ConstEvaluatable(..)) | PredicateKind::ConstEquate(..) | PredicateKind::Ambiguous => None, diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index d478677c3679..bbbd3347361e 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2781,11 +2781,6 @@ define_print! { ty::PredicateKind::ObjectSafe(trait_def_id) => { p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe") } - ty::PredicateKind::ClosureKind(closure_def_id, _closure_args, kind) => p!( - "the closure `", - print_value_path(closure_def_id, &[]), - write("` implements the trait `{}`", kind) - ), ty::PredicateKind::ConstEquate(c1, c2) => { p!("the constant `", print(c1), "` equals `", print(c2), "`") } diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 167a01ab7990..9ad4f9800b4e 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -1699,13 +1699,6 @@ impl<'tcx> Stable<'tcx> for ty::PredicateKind<'tcx> { PredicateKind::ObjectSafe(did) => { stable_mir::ty::PredicateKind::ObjectSafe(tables.trait_def(*did)) } - PredicateKind::ClosureKind(did, generic_args, closure_kind) => { - stable_mir::ty::PredicateKind::ClosureKind( - tables.closure_def(*did), - generic_args.stable(tables), - closure_kind.stable(tables), - ) - } PredicateKind::Subtype(subtype_predicate) => { stable_mir::ty::PredicateKind::SubType(subtype_predicate.stable(tables)) } diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs index 23ce0a301ce7..ded7874b62a5 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs @@ -406,8 +406,6 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { ty::PredicateKind::Coerce(predicate) => { self.compute_coerce_goal(Goal { param_env, predicate }) } - ty::PredicateKind::ClosureKind(def_id, args, kind) => self - .compute_closure_kind_goal(Goal { param_env, predicate: (def_id, args, kind) }), ty::PredicateKind::ObjectSafe(trait_def_id) => { self.compute_object_safe_goal(trait_def_id) } diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index f1d3091225c0..b73ec93b8248 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -135,7 +135,6 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { } ty::PredicateKind::Clause(_) | ty::PredicateKind::ObjectSafe(_) - | ty::PredicateKind::ClosureKind(_, _, _) | ty::PredicateKind::Ambiguous => { FulfillmentErrorCode::CodeSelectionError( SelectionError::Unimplemented, diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index dbf6749b5237..867b1c913ef3 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -822,7 +822,6 @@ impl<'tcx> AutoTraitFinder<'tcx> { | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..)) | ty::PredicateKind::AliasRelate(..) | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) | ty::PredicateKind::Subtype(..) // FIXME(generic_const_exprs): you can absolutely add this as a where clauses | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs index 5239725f5096..5f642ca9a792 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs @@ -786,11 +786,6 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { report_object_safety_error(self.tcx, span, trait_def_id, violations) } - ty::PredicateKind::ClosureKind(closure_def_id, closure_args, kind) => { - let found_kind = self.closure_kind(closure_args).unwrap(); - self.report_closure_error(&obligation, closure_def_id, found_kind, kind) - } - ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => { let ty = self.resolve_vars_if_possible(ty); match self.tcx.sess.opts.unstable_opts.trait_solver { diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index fb9cf51b513b..08544b4a93a9 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -350,7 +350,6 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..)) | ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) | ty::PredicateKind::ObjectSafe(_) - | ty::PredicateKind::ClosureKind(..) | ty::PredicateKind::Subtype(_) | ty::PredicateKind::Coerce(_) | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) @@ -411,19 +410,6 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { } } - ty::PredicateKind::ClosureKind(_, closure_args, kind) => { - match self.selcx.infcx.closure_kind(closure_args) { - Some(closure_kind) => { - if closure_kind.extends(kind) { - ProcessResult::Changed(vec![]) - } else { - ProcessResult::Error(CodeSelectionError(Unimplemented)) - } - } - None => ProcessResult::Unchanged, - } - } - ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => { match wf::obligations( self.selcx.infcx, diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs index 57df277f4b3a..94d6b15fe437 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs @@ -130,7 +130,6 @@ pub fn compute_implied_outlives_bounds_inner<'tcx>( | ty::PredicateKind::Subtype(..) | ty::PredicateKind::Coerce(..) | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) - | ty::PredicateKind::ClosureKind(..) | ty::PredicateKind::ObjectSafe(..) | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) | ty::PredicateKind::ConstEquate(..) diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 1529f736109a..a0ed773b62ca 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -291,8 +291,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } None => { - debug!("assemble_unboxed_candidates: closure_kind not yet known"); - candidates.vec.push(ClosureCandidate { is_const }); + if kind == ty::ClosureKind::FnOnce { + candidates.vec.push(ClosureCandidate { is_const }); + } else { + candidates.ambiguous = true; + } } } } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 2ab3ecbd5a3e..6cb76addd7d4 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -821,11 +821,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { &mut self, obligation: &PolyTraitObligation<'tcx>, ) -> Result>, SelectionError<'tcx>> { - let kind = self - .tcx() - .fn_trait_kind_from_def_id(obligation.predicate.def_id()) - .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation)); - // Okay to skip binder because the args on closure types never // touch bound regions, they just capture the in-scope // type/region parameters. @@ -835,15 +830,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }; let trait_ref = self.closure_trait_ref_unnormalized(obligation, args); - let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?; + let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?; debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations"); - nested.push(obligation.with( - self.tcx(), - ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, args, kind)), - )); - Ok(nested) } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 1ed0da59b64f..4bef36266550 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -885,19 +885,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::ClosureKind(_, closure_args, kind) => { - match self.infcx.closure_kind(closure_args) { - Some(closure_kind) => { - if closure_kind.extends(kind) { - Ok(EvaluatedToOk) - } else { - Ok(EvaluatedToErr) - } - } - None => Ok(EvaluatedToAmbig), - } - } - ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => { match const_evaluatable::is_const_evaluatable( self.infcx, diff --git a/compiler/rustc_traits/src/normalize_erasing_regions.rs b/compiler/rustc_traits/src/normalize_erasing_regions.rs index cb2a36cb998b..06486a100a9a 100644 --- a/compiler/rustc_traits/src/normalize_erasing_regions.rs +++ b/compiler/rustc_traits/src/normalize_erasing_regions.rs @@ -58,7 +58,6 @@ fn not_outlives_predicate(p: ty::Predicate<'_>) -> bool { | ty::PredicateKind::AliasRelate(..) | ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(..)) | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) | ty::PredicateKind::Subtype(..) | ty::PredicateKind::Coerce(..) | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) diff --git a/compiler/rustc_type_ir/src/predicate_kind.rs b/compiler/rustc_type_ir/src/predicate_kind.rs index da041ab1f355..f6a2dca4eee3 100644 --- a/compiler/rustc_type_ir/src/predicate_kind.rs +++ b/compiler/rustc_type_ir/src/predicate_kind.rs @@ -129,11 +129,6 @@ pub enum PredicateKind { /// Trait must be object-safe. ObjectSafe(I::DefId), - /// No direct syntax. May be thought of as `where T: FnFoo<...>` - /// for some generic args `...` and `T` being a closure type. - /// Satisfied (or refuted) once we know the closure's kind. - ClosureKind(I::DefId, I::GenericArgs, I::ClosureKind), - /// `T1 <: T2` /// /// This obligation is created most often when we have two @@ -173,7 +168,6 @@ where I::Term: Copy, I::CoercePredicate: Copy, I::SubtypePredicate: Copy, - I::ClosureKind: Copy, ClauseKind: Copy, { } @@ -183,9 +177,6 @@ impl PartialEq for PredicateKind { match (self, other) { (Self::Clause(l0), Self::Clause(r0)) => l0 == r0, (Self::ObjectSafe(l0), Self::ObjectSafe(r0)) => l0 == r0, - (Self::ClosureKind(l0, l1, l2), Self::ClosureKind(r0, r1, r2)) => { - l0 == r0 && l1 == r1 && l2 == r2 - } (Self::Subtype(l0), Self::Subtype(r0)) => l0 == r0, (Self::Coerce(l0), Self::Coerce(r0)) => l0 == r0, (Self::ConstEquate(l0, l1), Self::ConstEquate(r0, r1)) => l0 == r0 && l1 == r1, @@ -207,18 +198,12 @@ where I::Term: TypeFoldable, I::CoercePredicate: TypeFoldable, I::SubtypePredicate: TypeFoldable, - I::ClosureKind: TypeFoldable, ClauseKind: TypeFoldable, { fn try_fold_with>(self, folder: &mut F) -> Result { Ok(match self { PredicateKind::Clause(c) => PredicateKind::Clause(c.try_fold_with(folder)?), PredicateKind::ObjectSafe(d) => PredicateKind::ObjectSafe(d.try_fold_with(folder)?), - PredicateKind::ClosureKind(d, g, k) => PredicateKind::ClosureKind( - d.try_fold_with(folder)?, - g.try_fold_with(folder)?, - k.try_fold_with(folder)?, - ), PredicateKind::Subtype(s) => PredicateKind::Subtype(s.try_fold_with(folder)?), PredicateKind::Coerce(s) => PredicateKind::Coerce(s.try_fold_with(folder)?), PredicateKind::ConstEquate(a, b) => { @@ -242,18 +227,12 @@ where I::Term: TypeVisitable, I::CoercePredicate: TypeVisitable, I::SubtypePredicate: TypeVisitable, - I::ClosureKind: TypeVisitable, ClauseKind: TypeVisitable, { fn visit_with>(&self, visitor: &mut V) -> ControlFlow { match self { PredicateKind::Clause(p) => p.visit_with(visitor), PredicateKind::ObjectSafe(d) => d.visit_with(visitor), - PredicateKind::ClosureKind(d, g, k) => { - d.visit_with(visitor)?; - g.visit_with(visitor)?; - k.visit_with(visitor) - } PredicateKind::Subtype(s) => s.visit_with(visitor), PredicateKind::Coerce(s) => s.visit_with(visitor), PredicateKind::ConstEquate(a, b) => { @@ -313,9 +292,6 @@ impl fmt::Debug for PredicateKind { PredicateKind::ObjectSafe(trait_def_id) => { write!(f, "ObjectSafe({trait_def_id:?})") } - PredicateKind::ClosureKind(closure_def_id, closure_args, kind) => { - write!(f, "ClosureKind({closure_def_id:?}, {closure_args:?}, {kind:?})") - } PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({c1:?}, {c2:?})"), PredicateKind::Ambiguous => write!(f, "Ambiguous"), PredicateKind::AliasRelate(t1, t2, dir) => { diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index f0b11dce9aac..ae48fff78996 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -766,7 +766,6 @@ pub struct GenericPredicates { pub enum PredicateKind { Clause(ClauseKind), ObjectSafe(TraitDef), - ClosureKind(ClosureDef, GenericArgs, ClosureKind), SubType(SubtypePredicate), Coerce(CoercePredicate), ConstEquate(Const, Const), diff --git a/tests/ui/closure_context/issue-26046-fn-mut.stderr b/tests/ui/closure_context/issue-26046-fn-mut.stderr index eeb409452424..5f0b6fd451c4 100644 --- a/tests/ui/closure_context/issue-26046-fn-mut.stderr +++ b/tests/ui/closure_context/issue-26046-fn-mut.stderr @@ -1,16 +1,14 @@ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut` - --> $DIR/issue-26046-fn-mut.rs:4:19 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` + --> $DIR/issue-26046-fn-mut.rs:8:5 | -LL | let closure = || { - | ^^ this closure implements `FnMut`, not `Fn` -LL | num += 1; - | --- closure is `FnMut` because it mutates the variable `num` here -... LL | Box::new(closure) - | ----------------- the requirement to implement `Fn` derives from here + | ^^^^^^^^^^^^^^^^^ expected an `Fn()` closure, found `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` + = note: wrap the `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` implements `FnMut`, but it must implement `Fn`, which is more general = note: required for the cast from `Box<{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}>` to `Box<(dyn Fn() + 'static)>` error: aborting due to previous error -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/closure_context/issue-26046-fn-once.stderr b/tests/ui/closure_context/issue-26046-fn-once.stderr index 24773a1d7e35..da3dcf3e3af8 100644 --- a/tests/ui/closure_context/issue-26046-fn-once.stderr +++ b/tests/ui/closure_context/issue-26046-fn-once.stderr @@ -1,16 +1,14 @@ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/issue-26046-fn-once.rs:4:19 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` + --> $DIR/issue-26046-fn-once.rs:8:5 | -LL | let closure = move || { - | ^^^^^^^ this closure implements `FnOnce`, not `Fn` -LL | vec - | --- closure is `FnOnce` because it moves the variable `vec` out of its environment -... LL | Box::new(closure) - | ----------------- the requirement to implement `Fn` derives from here + | ^^^^^^^^^^^^^^^^^ expected an `Fn()` closure, found `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` + = note: wrap the `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` implements `FnOnce`, but it must implement `Fn`, which is more general = note: required for the cast from `Box<{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}>` to `Box<(dyn Fn() -> Vec + 'static)>` error: aborting due to previous error -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr index 309c63e52932..189f08c12e9c 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr @@ -1,16 +1,14 @@ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/closure-origin-array-diagnostics.rs:9:13 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` + --> $DIR/closure-origin-array-diagnostics.rs:12:15 | -LL | let c = || { - | ^^ this closure implements `FnOnce`, not `Fn` -LL | let [_, _s] = s; - | - closure is `FnOnce` because it moves the variable `s` out of its environment -LL | }; LL | expect_fn(c); - | --------- - the requirement to implement `Fn` derives from here + | --------- ^ expected an `Fn()` closure, found `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` | | | required by a bound introduced by this call | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` + = note: wrap the `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `expect_fn` --> $DIR/closure-origin-array-diagnostics.rs:5:17 | @@ -19,4 +17,4 @@ LL | fn expect_fn(_f: F) {} error: aborting due to previous error -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr index 3e77635f9e0c..75c49d312a58 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr @@ -1,16 +1,14 @@ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/closure-origin-tuple-diagnostics.rs:9:13 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` + --> $DIR/closure-origin-tuple-diagnostics.rs:12:15 | -LL | let c = || { - | ^^ this closure implements `FnOnce`, not `Fn` -LL | let s = s.1; - | --- closure is `FnOnce` because it moves the variable `s.1` out of its environment -LL | }; LL | expect_fn(c); - | --------- - the requirement to implement `Fn` derives from here + | --------- ^ expected an `Fn()` closure, found `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` | | | required by a bound introduced by this call | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` + = note: wrap the `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `expect_fn` --> $DIR/closure-origin-tuple-diagnostics.rs:5:17 | @@ -19,4 +17,4 @@ LL | fn expect_fn(_f: F) {} error: aborting due to previous error -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/closures/closure-wrong-kind.stderr b/tests/ui/closures/closure-wrong-kind.stderr index 9ea55d764f34..c1c830144384 100644 --- a/tests/ui/closures/closure-wrong-kind.stderr +++ b/tests/ui/closures/closure-wrong-kind.stderr @@ -1,15 +1,13 @@ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/closure-wrong-kind.rs:10:19 +error[E0277]: expected a `Fn(u32)` closure, found `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` + --> $DIR/closure-wrong-kind.rs:11:9 | -LL | let closure = |_| foo(x); - | ^^^ - closure is `FnOnce` because it moves the variable `x` out of its environment - | | - | this closure implements `FnOnce`, not `Fn` LL | bar(closure); - | --- ------- the requirement to implement `Fn` derives from here + | --- ^^^^^^^ expected an `Fn(u32)` closure, found `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` | | | required by a bound introduced by this call | + = help: the trait `Fn<(u32,)>` is not implemented for closure `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` + = note: `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `bar` --> $DIR/closure-wrong-kind.rs:6:11 | @@ -18,4 +16,4 @@ LL | fn bar(_: T) {} error: aborting due to previous error -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/issues/issue-34349.stderr b/tests/ui/issues/issue-34349.stderr index 8e9a16619f3b..1235f44f4aa6 100644 --- a/tests/ui/issues/issue-34349.stderr +++ b/tests/ui/issues/issue-34349.stderr @@ -1,16 +1,14 @@ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut` - --> $DIR/issue-34349.rs:16:17 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/issue-34349.rs:16:17: 16:19}` + --> $DIR/issue-34349.rs:21:11 | -LL | let diary = || { - | ^^ this closure implements `FnMut`, not `Fn` -LL | farewell.push_str("!!!"); - | -------- closure is `FnMut` because it mutates the variable `farewell` here -... LL | apply(diary); - | ----- ----- the requirement to implement `Fn` derives from here + | ----- ^^^^^ expected an `Fn()` closure, found `{closure@$DIR/issue-34349.rs:16:17: 16:19}` | | | required by a bound introduced by this call | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/issue-34349.rs:16:17: 16:19}` + = note: wrap the `{closure@$DIR/issue-34349.rs:16:17: 16:19}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/issue-34349.rs:16:17: 16:19}` implements `FnMut`, but it must implement `Fn`, which is more general note: required by a bound in `apply` --> $DIR/issue-34349.rs:11:32 | @@ -19,4 +17,4 @@ LL | fn apply(f: F) where F: Fn() { error: aborting due to previous error -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr b/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr index eba65a61803d..9a8c8123fbaf 100644 --- a/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr +++ b/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr @@ -1,57 +1,48 @@ -error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` - --> $DIR/move-ref-patterns-closure-captures.rs:9:14 +error[E0277]: expected a `FnMut()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` + --> $DIR/move-ref-patterns-closure-captures.rs:17:19 | -LL | let c1 = || { - | ^^ this closure implements `FnOnce`, not `FnMut` -... -LL | drop::(_x1); - | --- closure is `FnOnce` because it moves the variable `_x1` out of its environment -... LL | accept_fn_mut(&c1); - | ------------- --- the requirement to implement `FnMut` derives from here + | ------------- ^^^ expected an `FnMut()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` | | | required by a bound introduced by this call | + = help: the trait `FnMut<()>` is not implemented for closure `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` + = note: wrap the `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` implements `FnOnce`, but it must implement `FnMut`, which is more general note: required by a bound in `accept_fn_mut` --> $DIR/move-ref-patterns-closure-captures.rs:4:31 | LL | fn accept_fn_mut(_: &impl FnMut()) {} | ^^^^^^^ required by this bound in `accept_fn_mut` -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/move-ref-patterns-closure-captures.rs:9:14 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` + --> $DIR/move-ref-patterns-closure-captures.rs:18:15 | -LL | let c1 = || { - | ^^ this closure implements `FnOnce`, not `Fn` -... -LL | drop::(_x1); - | --- closure is `FnOnce` because it moves the variable `_x1` out of its environment -... LL | accept_fn(&c1); - | --------- --- the requirement to implement `Fn` derives from here + | --------- ^^^ expected an `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` | | | required by a bound introduced by this call | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` + = note: wrap the `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `accept_fn` --> $DIR/move-ref-patterns-closure-captures.rs:5:27 | LL | fn accept_fn(_: &impl Fn()) {} | ^^^^ required by this bound in `accept_fn` -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut` - --> $DIR/move-ref-patterns-closure-captures.rs:20:14 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` + --> $DIR/move-ref-patterns-closure-captures.rs:26:15 | -LL | let c2 = || { - | ^^ this closure implements `FnMut`, not `Fn` -... -LL | drop::<&mut U>(_x2); - | --- closure is `FnMut` because it mutates the variable `_x2` here -... LL | accept_fn(&c2); - | --------- --- the requirement to implement `Fn` derives from here + | --------- ^^^ expected an `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` | | | required by a bound introduced by this call | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` + = note: wrap the `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` implements `FnMut`, but it must implement `Fn`, which is more general note: required by a bound in `accept_fn` --> $DIR/move-ref-patterns-closure-captures.rs:5:27 | @@ -60,4 +51,4 @@ LL | fn accept_fn(_: &impl Fn()) {} error: aborting due to 3 previous errors -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr b/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr index 846a44ce4d7a..8a06d2f66bf1 100644 --- a/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr +++ b/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr @@ -1,15 +1,14 @@ -error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` - --> $DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13 +error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` + --> $DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:15:9 | -LL | let c = || drop(y.0); - | ^^ --- closure is `FnOnce` because it moves the variable `y` out of its environment - | | - | this closure implements `FnOnce`, not `Fn` LL | foo(c); - | --- - the requirement to implement `Fn` derives from here + | --- ^ expected an `Fn()` closure, found `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` | | | required by a bound introduced by this call | + = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` + = note: wrap the `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` in a closure with no arguments: `|| { /* code */ }` + = note: `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `foo` --> $DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:4:14 | @@ -20,4 +19,4 @@ LL | where F: Fn() error: aborting due to previous error -For more information about this error, try `rustc --explain E0525`. +For more information about this error, try `rustc --explain E0277`. From 128feaa2b40d063a834030d3ff9410c9327c5286 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 21 Nov 2023 04:20:18 +0000 Subject: [PATCH 15/66] Restore closure-kind error messages --- compiler/rustc_infer/src/infer/mod.rs | 6 ++- .../error_reporting/type_err_ctxt_ext.rs | 44 ++++++++++++++++- .../closure_context/issue-26046-fn-mut.stderr | 16 ++++--- .../issue-26046-fn-once.stderr | 16 ++++--- .../closure-origin-array-diagnostics.stderr | 16 ++++--- .../closure-origin-tuple-diagnostics.stderr | 16 ++++--- tests/ui/closures/closure-wrong-kind.stderr | 14 +++--- tests/ui/issues/issue-34349.stderr | 16 ++++--- .../move-ref-patterns-closure-captures.stderr | 47 +++++++++++-------- ...-infer-fn-once-move-from-projection.stderr | 15 +++--- 10 files changed, 136 insertions(+), 70 deletions(-) diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 956d097a5b2e..d6c7a24476f9 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -906,12 +906,14 @@ impl<'tcx> InferCtxt<'tcx> { self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot) } - pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> bool + pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, expected: T, actual: T) -> bool where T: at::ToTrace<'tcx>, { let origin = &ObligationCause::dummy(); - self.probe(|_| self.at(origin, param_env).sub(DefineOpaqueTypes::No, a, b).is_ok()) + self.probe(|_| { + self.at(origin, param_env).sub(DefineOpaqueTypes::No, expected, actual).is_ok() + }) } pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> bool diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs index 5f642ca9a792..fa24b2a40555 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs @@ -98,6 +98,12 @@ pub trait TypeErrCtxtExt<'tcx> { error: &SelectionError<'tcx>, ); + fn emit_specialized_closure_kind_error( + &self, + obligation: &PredicateObligation<'tcx>, + trait_ref: ty::PolyTraitRef<'tcx>, + ) -> Option; + fn fn_arg_obligation(&self, obligation: &PredicateObligation<'tcx>) -> bool; fn report_const_param_not_wf( @@ -411,6 +417,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => { let trait_predicate = bound_predicate.rebind(trait_predicate); let trait_predicate = self.resolve_vars_if_possible(trait_predicate); + let trait_ref = trait_predicate.to_poly_trait_ref(); + + if let Some(_guar) = self.emit_specialized_closure_kind_error(&obligation, trait_ref) { + return; + } // FIXME(effects) let predicate_is_const = false; @@ -425,7 +436,6 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // reported on the binding definition (#56607). return; } - let trait_ref = trait_predicate.to_poly_trait_ref(); let (post_message, pre_message, type_def, file_note) = self .get_parent_trait_ref(obligation.cause.code()) .map(|(t, s)| { @@ -922,6 +932,38 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.emit(); } + fn emit_specialized_closure_kind_error( + &self, + obligation: &PredicateObligation<'tcx>, + trait_ref: ty::PolyTraitRef<'tcx>, + ) -> Option { + if let ty::Closure(closure_def_id, closure_args) = *trait_ref.self_ty().skip_binder().kind() + && let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_ref.def_id()) + && let Some(found_kind) = self.closure_kind(closure_args) + && !found_kind.extends(expected_kind) + && let sig = closure_args.as_closure().sig() + && self.can_sub( + obligation.param_env, + trait_ref, + sig.map_bound(|sig| { + ty::TraitRef::new( + self.tcx, + trait_ref.def_id(), + [trait_ref.self_ty().skip_binder(), sig.inputs()[0]], + ) + }), + ) + { + let mut err = + self.report_closure_error(&obligation, closure_def_id, found_kind, expected_kind); + self.note_obligation_cause(&mut err, &obligation); + self.point_at_returns_when_relevant(&mut err, &obligation); + Some(err.emit()) + } else { + None + } + } + fn fn_arg_obligation(&self, obligation: &PredicateObligation<'tcx>) -> bool { if let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() diff --git a/tests/ui/closure_context/issue-26046-fn-mut.stderr b/tests/ui/closure_context/issue-26046-fn-mut.stderr index 5f0b6fd451c4..eeb409452424 100644 --- a/tests/ui/closure_context/issue-26046-fn-mut.stderr +++ b/tests/ui/closure_context/issue-26046-fn-mut.stderr @@ -1,14 +1,16 @@ -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` - --> $DIR/issue-26046-fn-mut.rs:8:5 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut` + --> $DIR/issue-26046-fn-mut.rs:4:19 | +LL | let closure = || { + | ^^ this closure implements `FnMut`, not `Fn` +LL | num += 1; + | --- closure is `FnMut` because it mutates the variable `num` here +... LL | Box::new(closure) - | ^^^^^^^^^^^^^^^^^ expected an `Fn()` closure, found `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` + | ----------------- the requirement to implement `Fn` derives from here | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` - = note: wrap the `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}` implements `FnMut`, but it must implement `Fn`, which is more general = note: required for the cast from `Box<{closure@$DIR/issue-26046-fn-mut.rs:4:19: 4:21}>` to `Box<(dyn Fn() + 'static)>` error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. diff --git a/tests/ui/closure_context/issue-26046-fn-once.stderr b/tests/ui/closure_context/issue-26046-fn-once.stderr index da3dcf3e3af8..24773a1d7e35 100644 --- a/tests/ui/closure_context/issue-26046-fn-once.stderr +++ b/tests/ui/closure_context/issue-26046-fn-once.stderr @@ -1,14 +1,16 @@ -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` - --> $DIR/issue-26046-fn-once.rs:8:5 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/issue-26046-fn-once.rs:4:19 | +LL | let closure = move || { + | ^^^^^^^ this closure implements `FnOnce`, not `Fn` +LL | vec + | --- closure is `FnOnce` because it moves the variable `vec` out of its environment +... LL | Box::new(closure) - | ^^^^^^^^^^^^^^^^^ expected an `Fn()` closure, found `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` + | ----------------- the requirement to implement `Fn` derives from here | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` - = note: wrap the `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}` implements `FnOnce`, but it must implement `Fn`, which is more general = note: required for the cast from `Box<{closure@$DIR/issue-26046-fn-once.rs:4:19: 4:26}>` to `Box<(dyn Fn() -> Vec + 'static)>` error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr index 189f08c12e9c..309c63e52932 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-array-diagnostics.stderr @@ -1,14 +1,16 @@ -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` - --> $DIR/closure-origin-array-diagnostics.rs:12:15 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/closure-origin-array-diagnostics.rs:9:13 | +LL | let c = || { + | ^^ this closure implements `FnOnce`, not `Fn` +LL | let [_, _s] = s; + | - closure is `FnOnce` because it moves the variable `s` out of its environment +LL | }; LL | expect_fn(c); - | --------- ^ expected an `Fn()` closure, found `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` + | --------- - the requirement to implement `Fn` derives from here | | | required by a bound introduced by this call | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` - = note: wrap the `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/closure-origin-array-diagnostics.rs:9:13: 9:15}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `expect_fn` --> $DIR/closure-origin-array-diagnostics.rs:5:17 | @@ -17,4 +19,4 @@ LL | fn expect_fn(_f: F) {} error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. diff --git a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr index 75c49d312a58..3e77635f9e0c 100644 --- a/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr +++ b/tests/ui/closures/2229_closure_analysis/diagnostics/closure-origin-tuple-diagnostics.stderr @@ -1,14 +1,16 @@ -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` - --> $DIR/closure-origin-tuple-diagnostics.rs:12:15 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/closure-origin-tuple-diagnostics.rs:9:13 | +LL | let c = || { + | ^^ this closure implements `FnOnce`, not `Fn` +LL | let s = s.1; + | --- closure is `FnOnce` because it moves the variable `s.1` out of its environment +LL | }; LL | expect_fn(c); - | --------- ^ expected an `Fn()` closure, found `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` + | --------- - the requirement to implement `Fn` derives from here | | | required by a bound introduced by this call | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` - = note: wrap the `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/closure-origin-tuple-diagnostics.rs:9:13: 9:15}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `expect_fn` --> $DIR/closure-origin-tuple-diagnostics.rs:5:17 | @@ -17,4 +19,4 @@ LL | fn expect_fn(_f: F) {} error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. diff --git a/tests/ui/closures/closure-wrong-kind.stderr b/tests/ui/closures/closure-wrong-kind.stderr index c1c830144384..9ea55d764f34 100644 --- a/tests/ui/closures/closure-wrong-kind.stderr +++ b/tests/ui/closures/closure-wrong-kind.stderr @@ -1,13 +1,15 @@ -error[E0277]: expected a `Fn(u32)` closure, found `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` - --> $DIR/closure-wrong-kind.rs:11:9 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/closure-wrong-kind.rs:10:19 | +LL | let closure = |_| foo(x); + | ^^^ - closure is `FnOnce` because it moves the variable `x` out of its environment + | | + | this closure implements `FnOnce`, not `Fn` LL | bar(closure); - | --- ^^^^^^^ expected an `Fn(u32)` closure, found `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` + | --- ------- the requirement to implement `Fn` derives from here | | | required by a bound introduced by this call | - = help: the trait `Fn<(u32,)>` is not implemented for closure `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` - = note: `{closure@$DIR/closure-wrong-kind.rs:10:19: 10:22}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `bar` --> $DIR/closure-wrong-kind.rs:6:11 | @@ -16,4 +18,4 @@ LL | fn bar(_: T) {} error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. diff --git a/tests/ui/issues/issue-34349.stderr b/tests/ui/issues/issue-34349.stderr index 1235f44f4aa6..8e9a16619f3b 100644 --- a/tests/ui/issues/issue-34349.stderr +++ b/tests/ui/issues/issue-34349.stderr @@ -1,14 +1,16 @@ -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/issue-34349.rs:16:17: 16:19}` - --> $DIR/issue-34349.rs:21:11 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut` + --> $DIR/issue-34349.rs:16:17 | +LL | let diary = || { + | ^^ this closure implements `FnMut`, not `Fn` +LL | farewell.push_str("!!!"); + | -------- closure is `FnMut` because it mutates the variable `farewell` here +... LL | apply(diary); - | ----- ^^^^^ expected an `Fn()` closure, found `{closure@$DIR/issue-34349.rs:16:17: 16:19}` + | ----- ----- the requirement to implement `Fn` derives from here | | | required by a bound introduced by this call | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/issue-34349.rs:16:17: 16:19}` - = note: wrap the `{closure@$DIR/issue-34349.rs:16:17: 16:19}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/issue-34349.rs:16:17: 16:19}` implements `FnMut`, but it must implement `Fn`, which is more general note: required by a bound in `apply` --> $DIR/issue-34349.rs:11:32 | @@ -17,4 +19,4 @@ LL | fn apply(f: F) where F: Fn() { error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. diff --git a/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr b/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr index 9a8c8123fbaf..eba65a61803d 100644 --- a/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr +++ b/tests/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr @@ -1,48 +1,57 @@ -error[E0277]: expected a `FnMut()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` - --> $DIR/move-ref-patterns-closure-captures.rs:17:19 +error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce` + --> $DIR/move-ref-patterns-closure-captures.rs:9:14 | +LL | let c1 = || { + | ^^ this closure implements `FnOnce`, not `FnMut` +... +LL | drop::(_x1); + | --- closure is `FnOnce` because it moves the variable `_x1` out of its environment +... LL | accept_fn_mut(&c1); - | ------------- ^^^ expected an `FnMut()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` + | ------------- --- the requirement to implement `FnMut` derives from here | | | required by a bound introduced by this call | - = help: the trait `FnMut<()>` is not implemented for closure `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` - = note: wrap the `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` implements `FnOnce`, but it must implement `FnMut`, which is more general note: required by a bound in `accept_fn_mut` --> $DIR/move-ref-patterns-closure-captures.rs:4:31 | LL | fn accept_fn_mut(_: &impl FnMut()) {} | ^^^^^^^ required by this bound in `accept_fn_mut` -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` - --> $DIR/move-ref-patterns-closure-captures.rs:18:15 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/move-ref-patterns-closure-captures.rs:9:14 | +LL | let c1 = || { + | ^^ this closure implements `FnOnce`, not `Fn` +... +LL | drop::(_x1); + | --- closure is `FnOnce` because it moves the variable `_x1` out of its environment +... LL | accept_fn(&c1); - | --------- ^^^ expected an `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` + | --------- --- the requirement to implement `Fn` derives from here | | | required by a bound introduced by this call | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` - = note: wrap the `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/move-ref-patterns-closure-captures.rs:9:14: 9:16}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `accept_fn` --> $DIR/move-ref-patterns-closure-captures.rs:5:27 | LL | fn accept_fn(_: &impl Fn()) {} | ^^^^ required by this bound in `accept_fn` -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` - --> $DIR/move-ref-patterns-closure-captures.rs:26:15 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut` + --> $DIR/move-ref-patterns-closure-captures.rs:20:14 | +LL | let c2 = || { + | ^^ this closure implements `FnMut`, not `Fn` +... +LL | drop::<&mut U>(_x2); + | --- closure is `FnMut` because it mutates the variable `_x2` here +... LL | accept_fn(&c2); - | --------- ^^^ expected an `Fn()` closure, found `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` + | --------- --- the requirement to implement `Fn` derives from here | | | required by a bound introduced by this call | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` - = note: wrap the `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/move-ref-patterns-closure-captures.rs:20:14: 20:16}` implements `FnMut`, but it must implement `Fn`, which is more general note: required by a bound in `accept_fn` --> $DIR/move-ref-patterns-closure-captures.rs:5:27 | @@ -51,4 +60,4 @@ LL | fn accept_fn(_: &impl Fn()) {} error: aborting due to 3 previous errors -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. diff --git a/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr b/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr index 8a06d2f66bf1..846a44ce4d7a 100644 --- a/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr +++ b/tests/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr @@ -1,14 +1,15 @@ -error[E0277]: expected a `Fn()` closure, found `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` - --> $DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:15:9 +error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` + --> $DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13 | +LL | let c = || drop(y.0); + | ^^ --- closure is `FnOnce` because it moves the variable `y` out of its environment + | | + | this closure implements `FnOnce`, not `Fn` LL | foo(c); - | --- ^ expected an `Fn()` closure, found `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` + | --- - the requirement to implement `Fn` derives from here | | | required by a bound introduced by this call | - = help: the trait `Fn<()>` is not implemented for closure `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` - = note: wrap the `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` in a closure with no arguments: `|| { /* code */ }` - = note: `{closure@$DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13: 14:15}` implements `FnOnce`, but it must implement `Fn`, which is more general note: required by a bound in `foo` --> $DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:4:14 | @@ -19,4 +20,4 @@ LL | where F: Fn() error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0525`. From e6f8edff3734ecfa55159da63343fbea3f1ee3a5 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Tue, 21 Nov 2023 13:43:11 -0500 Subject: [PATCH 16/66] Tighten up linkage settings for LLVM bindings --- compiler/rustc_codegen_llvm/src/lib.rs | 4 +- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 372 ++++++++++-------- compiler/rustc_codegen_llvm/src/llvm_util.rs | 4 +- .../rustc_llvm/llvm-wrapper/PassWrapper.cpp | 6 +- 4 files changed, 206 insertions(+), 180 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 3242e78ab7e4..8d809648aca7 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -104,7 +104,7 @@ struct TimeTraceProfiler { impl TimeTraceProfiler { fn new(enabled: bool) -> Self { if enabled { - unsafe { llvm::LLVMTimeTraceProfilerInitialize() } + unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() } } TimeTraceProfiler { enabled } } @@ -113,7 +113,7 @@ impl TimeTraceProfiler { impl Drop for TimeTraceProfiler { fn drop(&mut self) { if self.enabled { - unsafe { llvm::LLVMTimeTraceProfilerFinishThread() } + unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() } } } } diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 7fc02a95be0a..245baad26128 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -823,11 +823,7 @@ pub type GetSymbolsCallback = unsafe extern "C" fn(*mut c_void, *const c_char) - pub type GetSymbolsErrorCallback = unsafe extern "C" fn(*const c_char) -> *mut c_void; extern "C" { - pub fn LLVMRustInstallFatalErrorHandler(); - pub fn LLVMRustDisableSystemDialogsOnCrash(); - // Create and destroy contexts. - pub fn LLVMRustContextCreate(shouldDiscardNames: bool) -> &'static mut Context; pub fn LLVMContextDispose(C: &'static mut Context); pub fn LLVMGetMDKindIDInContext(C: &Context, Name: *const c_char, SLen: c_uint) -> c_uint; @@ -843,9 +839,6 @@ extern "C" { /// See Module::setModuleInlineAsm. pub fn LLVMAppendModuleInlineAsm(M: &Module, Asm: *const c_char, Len: size_t); - /// See llvm::LLVMTypeKind::getTypeID. - pub fn LLVMRustGetTypeKind(Ty: &Type) -> TypeKind; - // Operations on integer types pub fn LLVMInt1TypeInContext(C: &Context) -> &Type; pub fn LLVMInt8TypeInContext(C: &Context) -> &Type; @@ -879,7 +872,6 @@ extern "C" { ) -> &'a Type; // Operations on array, pointer, and vector types (sequence types) - pub fn LLVMRustArrayType(ElementType: &Type, ElementCount: u64) -> &Type; pub fn LLVMPointerTypeInContext(C: &Context, AddressSpace: c_uint) -> &Type; pub fn LLVMVectorType(ElementType: &Type, ElementCount: c_uint) -> &Type; @@ -898,10 +890,8 @@ extern "C" { pub fn LLVMReplaceAllUsesWith<'a>(OldVal: &'a Value, NewVal: &'a Value); pub fn LLVMSetMetadata<'a>(Val: &'a Value, KindID: c_uint, Node: &'a Value); pub fn LLVMGlobalSetMetadata<'a>(Val: &'a Value, KindID: c_uint, Metadata: &'a Metadata); - pub fn LLVMRustGlobalAddMetadata<'a>(Val: &'a Value, KindID: c_uint, Metadata: &'a Metadata); pub fn LLVMValueAsMetadata(Node: &Value) -> &Metadata; pub fn LLVMIsAFunction(Val: &Value) -> Option<&Value>; - pub fn LLVMRustIsNonGVFunctionPointerTy(Val: &Value) -> bool; // Operations on constants of any type pub fn LLVMConstNull(Ty: &Type) -> &Value; @@ -931,13 +921,6 @@ extern "C" { pub fn LLVMConstInt(IntTy: &Type, N: c_ulonglong, SignExtend: Bool) -> &Value; pub fn LLVMConstIntOfArbitraryPrecision(IntTy: &Type, Wn: c_uint, Ws: *const u64) -> &Value; pub fn LLVMConstReal(RealTy: &Type, N: f64) -> &Value; - pub fn LLVMRustConstIntGetZExtValue(ConstantVal: &ConstantInt, Value: &mut u64) -> bool; - pub fn LLVMRustConstInt128Get( - ConstantVal: &ConstantInt, - SExt: bool, - high: &mut u64, - low: &mut u64, - ) -> bool; // Operations on composite constants pub fn LLVMConstStringInContext( @@ -977,12 +960,7 @@ extern "C" { // Operations on global variables, functions, and aliases (globals) pub fn LLVMIsDeclaration(Global: &Value) -> Bool; - pub fn LLVMRustGetLinkage(Global: &Value) -> Linkage; - pub fn LLVMRustSetLinkage(Global: &Value, RustLinkage: Linkage); pub fn LLVMSetSection(Global: &Value, Section: *const c_char); - pub fn LLVMRustGetVisibility(Global: &Value) -> Visibility; - pub fn LLVMRustSetVisibility(Global: &Value, Viz: Visibility); - pub fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool); pub fn LLVMGetAlignment(Global: &Value) -> c_uint; pub fn LLVMSetAlignment(Global: &Value, Bytes: c_uint); pub fn LLVMSetDLLStorageClass(V: &Value, C: DLLStorageClass); @@ -991,13 +969,6 @@ extern "C" { pub fn LLVMIsAGlobalVariable(GlobalVar: &Value) -> Option<&Value>; pub fn LLVMAddGlobal<'a>(M: &'a Module, Ty: &'a Type, Name: *const c_char) -> &'a Value; pub fn LLVMGetNamedGlobal(M: &Module, Name: *const c_char) -> Option<&Value>; - pub fn LLVMRustGetOrInsertGlobal<'a>( - M: &'a Module, - Name: *const c_char, - NameLen: size_t, - T: &'a Type, - ) -> &'a Value; - pub fn LLVMRustInsertPrivateGlobal<'a>(M: &'a Module, T: &'a Type) -> &'a Value; pub fn LLVMGetFirstGlobal(M: &Module) -> Option<&Value>; pub fn LLVMGetNextGlobal(GlobalVar: &Value) -> Option<&Value>; pub fn LLVMDeleteGlobal(GlobalVar: &Value); @@ -1007,16 +978,9 @@ extern "C" { pub fn LLVMSetThreadLocalMode(GlobalVar: &Value, Mode: ThreadLocalMode); pub fn LLVMIsGlobalConstant(GlobalVar: &Value) -> Bool; pub fn LLVMSetGlobalConstant(GlobalVar: &Value, IsConstant: Bool); - pub fn LLVMRustGetNamedValue( - M: &Module, - Name: *const c_char, - NameLen: size_t, - ) -> Option<&Value>; pub fn LLVMSetTailCall(CallInst: &Value, IsTailCall: Bool); - pub fn LLVMRustSetTailCallKind(CallInst: &Value, TKC: TailCallKind); // Operations on attributes - pub fn LLVMRustCreateAttrNoValue(C: &Context, attr: AttributeKind) -> &Attribute; pub fn LLVMCreateStringAttribute( C: &Context, Name: *const c_char, @@ -1024,31 +988,9 @@ extern "C" { Value: *const c_char, ValueLen: c_uint, ) -> &Attribute; - pub fn LLVMRustCreateAlignmentAttr(C: &Context, bytes: u64) -> &Attribute; - pub fn LLVMRustCreateDereferenceableAttr(C: &Context, bytes: u64) -> &Attribute; - pub fn LLVMRustCreateDereferenceableOrNullAttr(C: &Context, bytes: u64) -> &Attribute; - pub fn LLVMRustCreateByValAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute; - pub fn LLVMRustCreateStructRetAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute; - pub fn LLVMRustCreateElementTypeAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute; - pub fn LLVMRustCreateUWTableAttr(C: &Context, async_: bool) -> &Attribute; - pub fn LLVMRustCreateAllocSizeAttr(C: &Context, size_arg: u32) -> &Attribute; - pub fn LLVMRustCreateAllocKindAttr(C: &Context, size_arg: u64) -> &Attribute; - pub fn LLVMRustCreateMemoryEffectsAttr(C: &Context, effects: MemoryEffects) -> &Attribute; // Operations on functions - pub fn LLVMRustGetOrInsertFunction<'a>( - M: &'a Module, - Name: *const c_char, - NameLen: size_t, - FunctionTy: &'a Type, - ) -> &'a Value; pub fn LLVMSetFunctionCallConv(Fn: &Value, CC: c_uint); - pub fn LLVMRustAddFunctionAttributes<'a>( - Fn: &'a Value, - index: c_uint, - Attrs: *const &'a Attribute, - AttrsLen: size_t, - ); // Operations on parameters pub fn LLVMIsAArgument(Val: &Value) -> Option<&Value>; @@ -1069,12 +1011,6 @@ extern "C" { // Operations on call sites pub fn LLVMSetInstructionCallConv(Instr: &Value, CC: c_uint); - pub fn LLVMRustAddCallSiteAttributes<'a>( - Instr: &'a Value, - index: c_uint, - Attrs: *const &'a Attribute, - AttrsLen: size_t, - ); // Operations on load/store instructions (only) pub fn LLVMSetVolatile(MemoryAccessInst: &Value, volatile: Bool); @@ -1112,18 +1048,6 @@ extern "C" { Else: &'a BasicBlock, NumCases: c_uint, ) -> &'a Value; - pub fn LLVMRustBuildInvoke<'a>( - B: &Builder<'a>, - Ty: &'a Type, - Fn: &'a Value, - Args: *const &'a Value, - NumArgs: c_uint, - Then: &'a BasicBlock, - Catch: &'a BasicBlock, - OpBundles: *const &OperandBundleDef<'a>, - NumOpBundles: c_uint, - Name: *const c_char, - ) -> &'a Value; pub fn LLVMBuildLandingPad<'a>( B: &Builder<'a>, Ty: &'a Type, @@ -1337,7 +1261,6 @@ extern "C" { pub fn LLVMBuildNeg<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char) -> &'a Value; pub fn LLVMBuildFNeg<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char) -> &'a Value; pub fn LLVMBuildNot<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char) -> &'a Value; - pub fn LLVMRustSetFastMath(Instr: &Value); // Memory pub fn LLVMBuildAlloca<'a>(B: &Builder<'a>, Ty: &'a Type, Name: *const c_char) -> &'a Value; @@ -1485,42 +1408,6 @@ extern "C" { // Miscellaneous instructions pub fn LLVMBuildPhi<'a>(B: &Builder<'a>, Ty: &'a Type, Name: *const c_char) -> &'a Value; - pub fn LLVMRustGetInstrProfIncrementIntrinsic(M: &Module) -> &Value; - pub fn LLVMRustBuildCall<'a>( - B: &Builder<'a>, - Ty: &'a Type, - Fn: &'a Value, - Args: *const &'a Value, - NumArgs: c_uint, - OpBundles: *const &OperandBundleDef<'a>, - NumOpBundles: c_uint, - ) -> &'a Value; - pub fn LLVMRustBuildMemCpy<'a>( - B: &Builder<'a>, - Dst: &'a Value, - DstAlign: c_uint, - Src: &'a Value, - SrcAlign: c_uint, - Size: &'a Value, - IsVolatile: bool, - ) -> &'a Value; - pub fn LLVMRustBuildMemMove<'a>( - B: &Builder<'a>, - Dst: &'a Value, - DstAlign: c_uint, - Src: &'a Value, - SrcAlign: c_uint, - Size: &'a Value, - IsVolatile: bool, - ) -> &'a Value; - pub fn LLVMRustBuildMemSet<'a>( - B: &Builder<'a>, - Dst: &'a Value, - DstAlign: c_uint, - Val: &'a Value, - Size: &'a Value, - IsVolatile: bool, - ) -> &'a Value; pub fn LLVMBuildSelect<'a>( B: &Builder<'a>, If: &'a Value, @@ -1568,6 +1455,202 @@ extern "C" { Name: *const c_char, ) -> &'a Value; + // Atomic Operations + pub fn LLVMBuildAtomicCmpXchg<'a>( + B: &Builder<'a>, + LHS: &'a Value, + CMP: &'a Value, + RHS: &'a Value, + Order: AtomicOrdering, + FailureOrder: AtomicOrdering, + SingleThreaded: Bool, + ) -> &'a Value; + + pub fn LLVMSetWeak(CmpXchgInst: &Value, IsWeak: Bool); + + pub fn LLVMBuildAtomicRMW<'a>( + B: &Builder<'a>, + Op: AtomicRmwBinOp, + LHS: &'a Value, + RHS: &'a Value, + Order: AtomicOrdering, + SingleThreaded: Bool, + ) -> &'a Value; + + pub fn LLVMBuildFence<'a>( + B: &Builder<'a>, + Order: AtomicOrdering, + SingleThreaded: Bool, + Name: *const c_char, + ) -> &'a Value; + + /// Writes a module to the specified path. Returns 0 on success. + pub fn LLVMWriteBitcodeToFile(M: &Module, Path: *const c_char) -> c_int; + + /// Creates a legacy pass manager -- only used for final codegen. + pub fn LLVMCreatePassManager<'a>() -> &'a mut PassManager<'a>; + + pub fn LLVMAddAnalysisPasses<'a>(T: &'a TargetMachine, PM: &PassManager<'a>); + + pub fn LLVMGetHostCPUFeatures() -> *mut c_char; + + pub fn LLVMDisposeMessage(message: *mut c_char); + + pub fn LLVMIsMultithreaded() -> Bool; + + pub fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type; + + pub fn LLVMStructSetBody<'a>( + StructTy: &'a Type, + ElementTypes: *const &'a Type, + ElementCount: c_uint, + Packed: Bool, + ); + + pub fn LLVMMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value; + + pub fn LLVMSetUnnamedAddress(Global: &Value, UnnamedAddr: UnnamedAddr); + + pub fn LLVMIsAConstantInt(value_ref: &Value) -> Option<&ConstantInt>; +} + +#[link(name = "llvm-wrapper", kind = "static")] +extern "C" { + pub fn LLVMRustInstallFatalErrorHandler(); + pub fn LLVMRustDisableSystemDialogsOnCrash(); + + // Create and destroy contexts. + pub fn LLVMRustContextCreate(shouldDiscardNames: bool) -> &'static mut Context; + + /// See llvm::LLVMTypeKind::getTypeID. + pub fn LLVMRustGetTypeKind(Ty: &Type) -> TypeKind; + + // Operations on array, pointer, and vector types (sequence types) + pub fn LLVMRustArrayType(ElementType: &Type, ElementCount: u64) -> &Type; + + // Operations on all values + pub fn LLVMRustGlobalAddMetadata<'a>(Val: &'a Value, KindID: c_uint, Metadata: &'a Metadata); + pub fn LLVMRustIsNonGVFunctionPointerTy(Val: &Value) -> bool; + + // Operations on scalar constants + pub fn LLVMRustConstIntGetZExtValue(ConstantVal: &ConstantInt, Value: &mut u64) -> bool; + pub fn LLVMRustConstInt128Get( + ConstantVal: &ConstantInt, + SExt: bool, + high: &mut u64, + low: &mut u64, + ) -> bool; + + // Operations on global variables, functions, and aliases (globals) + pub fn LLVMRustGetLinkage(Global: &Value) -> Linkage; + pub fn LLVMRustSetLinkage(Global: &Value, RustLinkage: Linkage); + pub fn LLVMRustGetVisibility(Global: &Value) -> Visibility; + pub fn LLVMRustSetVisibility(Global: &Value, Viz: Visibility); + pub fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool); + + // Operations on global variables + pub fn LLVMRustGetOrInsertGlobal<'a>( + M: &'a Module, + Name: *const c_char, + NameLen: size_t, + T: &'a Type, + ) -> &'a Value; + pub fn LLVMRustInsertPrivateGlobal<'a>(M: &'a Module, T: &'a Type) -> &'a Value; + pub fn LLVMRustGetNamedValue( + M: &Module, + Name: *const c_char, + NameLen: size_t, + ) -> Option<&Value>; + pub fn LLVMRustSetTailCallKind(CallInst: &Value, TKC: TailCallKind); + + // Operations on attributes + pub fn LLVMRustCreateAttrNoValue(C: &Context, attr: AttributeKind) -> &Attribute; + pub fn LLVMRustCreateAlignmentAttr(C: &Context, bytes: u64) -> &Attribute; + pub fn LLVMRustCreateDereferenceableAttr(C: &Context, bytes: u64) -> &Attribute; + pub fn LLVMRustCreateDereferenceableOrNullAttr(C: &Context, bytes: u64) -> &Attribute; + pub fn LLVMRustCreateByValAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute; + pub fn LLVMRustCreateStructRetAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute; + pub fn LLVMRustCreateElementTypeAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute; + pub fn LLVMRustCreateUWTableAttr(C: &Context, async_: bool) -> &Attribute; + pub fn LLVMRustCreateAllocSizeAttr(C: &Context, size_arg: u32) -> &Attribute; + pub fn LLVMRustCreateAllocKindAttr(C: &Context, size_arg: u64) -> &Attribute; + pub fn LLVMRustCreateMemoryEffectsAttr(C: &Context, effects: MemoryEffects) -> &Attribute; + + // Operations on functions + pub fn LLVMRustGetOrInsertFunction<'a>( + M: &'a Module, + Name: *const c_char, + NameLen: size_t, + FunctionTy: &'a Type, + ) -> &'a Value; + pub fn LLVMRustAddFunctionAttributes<'a>( + Fn: &'a Value, + index: c_uint, + Attrs: *const &'a Attribute, + AttrsLen: size_t, + ); + + // Operations on call sites + pub fn LLVMRustAddCallSiteAttributes<'a>( + Instr: &'a Value, + index: c_uint, + Attrs: *const &'a Attribute, + AttrsLen: size_t, + ); + + pub fn LLVMRustBuildInvoke<'a>( + B: &Builder<'a>, + Ty: &'a Type, + Fn: &'a Value, + Args: *const &'a Value, + NumArgs: c_uint, + Then: &'a BasicBlock, + Catch: &'a BasicBlock, + OpBundles: *const &OperandBundleDef<'a>, + NumOpBundles: c_uint, + Name: *const c_char, + ) -> &'a Value; + + pub fn LLVMRustSetFastMath(Instr: &Value); + + // Miscellaneous instructions + pub fn LLVMRustGetInstrProfIncrementIntrinsic(M: &Module) -> &Value; + pub fn LLVMRustBuildCall<'a>( + B: &Builder<'a>, + Ty: &'a Type, + Fn: &'a Value, + Args: *const &'a Value, + NumArgs: c_uint, + OpBundles: *const &OperandBundleDef<'a>, + NumOpBundles: c_uint, + ) -> &'a Value; + pub fn LLVMRustBuildMemCpy<'a>( + B: &Builder<'a>, + Dst: &'a Value, + DstAlign: c_uint, + Src: &'a Value, + SrcAlign: c_uint, + Size: &'a Value, + IsVolatile: bool, + ) -> &'a Value; + pub fn LLVMRustBuildMemMove<'a>( + B: &Builder<'a>, + Dst: &'a Value, + DstAlign: c_uint, + Src: &'a Value, + SrcAlign: c_uint, + Size: &'a Value, + IsVolatile: bool, + ) -> &'a Value; + pub fn LLVMRustBuildMemSet<'a>( + B: &Builder<'a>, + Dst: &'a Value, + DstAlign: c_uint, + Val: &'a Value, + Size: &'a Value, + IsVolatile: bool, + ) -> &'a Value; + pub fn LLVMRustBuildVectorReduceFAdd<'a>( B: &Builder<'a>, Acc: &'a Value, @@ -1623,53 +1706,11 @@ extern "C" { Order: AtomicOrdering, ) -> &'a Value; - pub fn LLVMBuildAtomicCmpXchg<'a>( - B: &Builder<'a>, - LHS: &'a Value, - CMP: &'a Value, - RHS: &'a Value, - Order: AtomicOrdering, - FailureOrder: AtomicOrdering, - SingleThreaded: Bool, - ) -> &'a Value; + pub fn LLVMRustTimeTraceProfilerInitialize(); - pub fn LLVMSetWeak(CmpXchgInst: &Value, IsWeak: Bool); + pub fn LLVMRustTimeTraceProfilerFinishThread(); - pub fn LLVMBuildAtomicRMW<'a>( - B: &Builder<'a>, - Op: AtomicRmwBinOp, - LHS: &'a Value, - RHS: &'a Value, - Order: AtomicOrdering, - SingleThreaded: Bool, - ) -> &'a Value; - - pub fn LLVMBuildFence<'a>( - B: &Builder<'a>, - Order: AtomicOrdering, - SingleThreaded: Bool, - Name: *const c_char, - ) -> &'a Value; - - /// Writes a module to the specified path. Returns 0 on success. - pub fn LLVMWriteBitcodeToFile(M: &Module, Path: *const c_char) -> c_int; - - /// Creates a legacy pass manager -- only used for final codegen. - pub fn LLVMCreatePassManager<'a>() -> &'a mut PassManager<'a>; - - pub fn LLVMTimeTraceProfilerInitialize(); - - pub fn LLVMTimeTraceProfilerFinishThread(); - - pub fn LLVMTimeTraceProfilerFinish(FileName: *const c_char); - - pub fn LLVMAddAnalysisPasses<'a>(T: &'a TargetMachine, PM: &PassManager<'a>); - - pub fn LLVMGetHostCPUFeatures() -> *mut c_char; - - pub fn LLVMDisposeMessage(message: *mut c_char); - - pub fn LLVMIsMultithreaded() -> Bool; + pub fn LLVMRustTimeTraceProfilerFinish(FileName: *const c_char); /// Returns a string describing the last error caused by an LLVMRust* call. pub fn LLVMRustGetLastError() -> *const c_char; @@ -1680,15 +1721,6 @@ extern "C" { /// Print the statistics since static dtors aren't picking them up. pub fn LLVMRustPrintStatistics(size: *const size_t) -> *const c_char; - pub fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type; - - pub fn LLVMStructSetBody<'a>( - StructTy: &'a Type, - ElementTypes: *const &'a Type, - ElementCount: c_uint, - Packed: Bool, - ); - /// Prepares inline assembly. pub fn LLVMRustInlineAsm( Ty: &Type, @@ -1761,8 +1793,6 @@ extern "C" { ); pub fn LLVMRustHasModuleFlag(M: &Module, name: *const c_char, len: size_t) -> bool; - pub fn LLVMMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value; - pub fn LLVMRustDIBuilderCreate(M: &Module) -> &mut DIBuilder<'_>; pub fn LLVMRustDIBuilderDispose<'a>(Builder: &'a mut DIBuilder<'a>); @@ -2052,8 +2082,6 @@ extern "C" { UniqueIdLen: size_t, ) -> &'a DIDerivedType; - pub fn LLVMSetUnnamedAddress(Global: &Value, UnnamedAddr: UnnamedAddr); - pub fn LLVMRustDIBuilderCreateTemplateTypeParameter<'a>( Builder: &DIBuilder<'a>, Scope: Option<&'a DIScope>, @@ -2092,8 +2120,6 @@ extern "C" { #[allow(improper_ctypes)] pub fn LLVMRustWriteValueToString(value_ref: &Value, s: &RustString); - pub fn LLVMIsAConstantInt(value_ref: &Value) -> Option<&ConstantInt>; - pub fn LLVMRustHasFeature(T: &TargetMachine, s: *const c_char) -> bool; pub fn LLVMRustPrintTargetCPUs( diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index c86bf81fc131..7c29bb080082 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -121,7 +121,7 @@ unsafe fn configure_llvm(sess: &Session) { } if sess.opts.unstable_opts.llvm_time_trace { - llvm::LLVMTimeTraceProfilerInitialize(); + llvm::LLVMRustTimeTraceProfilerInitialize(); } rustc_llvm::initialize_available_targets(); @@ -132,7 +132,7 @@ unsafe fn configure_llvm(sess: &Session) { pub fn time_trace_profiler_finish(file_name: &Path) { unsafe { let file_name = path_to_c_string(file_name); - llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr()); + llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr()); } } diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index 31565db1b792..b4c8fb1a2f1d 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -60,17 +60,17 @@ typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef; DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef) DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef) -extern "C" void LLVMTimeTraceProfilerInitialize() { +extern "C" void LLVMRustTimeTraceProfilerInitialize() { timeTraceProfilerInitialize( /* TimeTraceGranularity */ 0, /* ProcName */ "rustc"); } -extern "C" void LLVMTimeTraceProfilerFinishThread() { +extern "C" void LLVMRustTimeTraceProfilerFinishThread() { timeTraceProfilerFinishThread(); } -extern "C" void LLVMTimeTraceProfilerFinish(const char* FileName) { +extern "C" void LLVMRustTimeTraceProfilerFinish(const char* FileName) { StringRef FN(FileName); std::error_code EC; raw_fd_ostream OS(FN, EC, sys::fs::CD_CreateAlways); From 21a870515b18e5b2b90435d0f1a6d3089b5217ae Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Tue, 21 Nov 2023 20:07:32 +0100 Subject: [PATCH 17/66] Fix `clippy::needless_borrow` in the compiler `x clippy compiler -Aclippy::all -Wclippy::needless_borrow --fix`. Then I had to remove a few unnecessary parens and muts that were exposed now. --- compiler/rustc_abi/src/layout.rs | 6 +- compiler/rustc_ast/src/attr/mod.rs | 2 +- compiler/rustc_ast_lowering/src/expr.rs | 8 +- compiler/rustc_ast_lowering/src/format.rs | 4 +- compiler/rustc_ast_lowering/src/index.rs | 2 +- compiler/rustc_ast_lowering/src/item.rs | 17 +-- compiler/rustc_ast_lowering/src/lib.rs | 16 ++- compiler/rustc_ast_lowering/src/path.rs | 6 +- .../rustc_ast_passes/src/ast_validation.rs | 6 +- compiler/rustc_ast_passes/src/feature_gate.rs | 6 +- compiler/rustc_ast_pretty/src/pprust/state.rs | 4 +- .../rustc_ast_pretty/src/pprust/state/item.rs | 2 +- compiler/rustc_attr/src/builtin.rs | 2 +- compiler/rustc_borrowck/src/borrow_set.rs | 6 +- .../src/diagnostics/conflict_errors.rs | 32 +++--- .../src/diagnostics/explain_borrow.rs | 2 +- .../rustc_borrowck/src/diagnostics/mod.rs | 6 +- .../src/diagnostics/move_errors.rs | 4 +- .../src/diagnostics/region_errors.rs | 6 +- .../src/diagnostics/region_name.rs | 2 +- compiler/rustc_borrowck/src/invalidation.rs | 4 +- compiler/rustc_borrowck/src/lib.rs | 18 +-- compiler/rustc_borrowck/src/nll.rs | 12 +- .../src/type_check/free_region_relations.rs | 2 +- .../src/type_check/liveness/local_use_map.rs | 2 +- .../src/type_check/liveness/mod.rs | 4 +- .../src/type_check/liveness/polonius.rs | 2 +- .../src/type_check/liveness/trace.rs | 10 +- compiler/rustc_borrowck/src/type_check/mod.rs | 34 +++--- compiler/rustc_borrowck/src/used_muts.rs | 2 +- .../src/cfg_accessible.rs | 2 +- compiler/rustc_builtin_macros/src/cfg_eval.rs | 28 ++--- .../rustc_builtin_macros/src/cmdline_attrs.rs | 2 +- .../rustc_builtin_macros/src/concat_bytes.rs | 2 +- compiler/rustc_builtin_macros/src/derive.rs | 6 +- .../src/deriving/generic/mod.rs | 6 +- .../src/deriving/generic/ty.rs | 2 +- compiler/rustc_builtin_macros/src/format.rs | 5 +- .../rustc_builtin_macros/src/source_util.rs | 4 +- compiler/rustc_builtin_macros/src/test.rs | 10 +- .../rustc_builtin_macros/src/test_harness.rs | 4 +- compiler/rustc_builtin_macros/src/util.rs | 2 +- compiler/rustc_codegen_llvm/src/abi.rs | 2 +- compiler/rustc_codegen_llvm/src/allocator.rs | 2 +- compiler/rustc_codegen_llvm/src/attributes.rs | 4 +- .../rustc_codegen_llvm/src/back/archive.rs | 2 +- compiler/rustc_codegen_llvm/src/back/write.rs | 4 +- compiler/rustc_codegen_llvm/src/callee.rs | 2 +- compiler/rustc_codegen_llvm/src/consts.rs | 2 +- .../src/coverageinfo/mapgen.rs | 2 +- .../src/debuginfo/metadata.rs | 2 +- .../src/debuginfo/metadata/enums/cpp_like.rs | 2 +- .../src/debuginfo/metadata/enums/native.rs | 2 +- compiler/rustc_codegen_llvm/src/llvm_util.rs | 3 +- .../src/assert_module_sources.rs | 2 +- .../rustc_codegen_ssa/src/back/archive.rs | 3 +- compiler/rustc_codegen_ssa/src/back/link.rs | 34 +++--- compiler/rustc_codegen_ssa/src/back/linker.rs | 8 +- .../src/back/symbol_export.rs | 2 +- compiler/rustc_codegen_ssa/src/back/write.rs | 6 +- compiler/rustc_codegen_ssa/src/base.rs | 13 +-- .../rustc_codegen_ssa/src/codegen_attrs.rs | 8 +- .../src/debuginfo/type_names.rs | 2 +- compiler/rustc_codegen_ssa/src/mir/analyze.rs | 4 +- compiler/rustc_codegen_ssa/src/mir/block.rs | 43 ++++--- .../rustc_codegen_ssa/src/mir/debuginfo.rs | 4 +- compiler/rustc_codegen_ssa/src/mir/mod.rs | 6 +- compiler/rustc_codegen_ssa/src/mir/rvalue.rs | 2 +- compiler/rustc_codegen_ssa/src/mono_item.rs | 8 +- .../src/const_eval/eval_queries.rs | 2 +- .../src/const_eval/machine.rs | 2 +- .../src/const_eval/valtrees.rs | 2 +- .../rustc_const_eval/src/interpret/cast.rs | 2 +- .../rustc_const_eval/src/interpret/intern.rs | 2 +- .../src/interpret/intrinsics.rs | 4 +- .../src/interpret/operator.rs | 2 +- .../rustc_const_eval/src/interpret/place.rs | 4 +- .../src/interpret/terminator.rs | 6 +- .../src/interpret/validity.rs | 2 +- .../rustc_const_eval/src/interpret/visitor.rs | 4 +- .../src/transform/check_consts/check.rs | 18 +-- .../src/transform/check_consts/mod.rs | 2 +- .../src/transform/check_consts/ops.rs | 2 +- .../check_consts/post_drop_elaboration.rs | 2 +- .../src/transform/promote_consts.rs | 6 +- compiler/rustc_data_structures/src/sharded.rs | 4 +- .../src/annotate_snippet_emitter_writer.rs | 4 +- compiler/rustc_errors/src/emitter.rs | 8 +- compiler/rustc_expand/src/base.rs | 12 +- compiler/rustc_expand/src/config.rs | 4 +- compiler/rustc_expand/src/expand.rs | 16 +-- compiler/rustc_expand/src/mbe/macro_check.rs | 2 +- compiler/rustc_expand/src/mbe/macro_parser.rs | 2 +- compiler/rustc_expand/src/mbe/macro_rules.rs | 10 +- compiler/rustc_expand/src/mbe/quoted.rs | 12 +- compiler/rustc_expand/src/mbe/transcribe.rs | 8 +- compiler/rustc_expand/src/module.rs | 4 +- .../rustc_expand/src/proc_macro_server.rs | 2 +- .../rustc_hir_analysis/src/astconv/errors.rs | 2 +- .../rustc_hir_analysis/src/astconv/lint.rs | 4 +- .../rustc_hir_analysis/src/astconv/mod.rs | 4 +- compiler/rustc_hir_analysis/src/autoderef.rs | 2 +- .../rustc_hir_analysis/src/check/check.rs | 12 +- .../src/check/compare_impl_item.rs | 4 +- .../src/check/intrinsicck.rs | 12 +- .../rustc_hir_analysis/src/check/region.rs | 36 +++--- .../rustc_hir_analysis/src/check/wfcheck.rs | 8 +- .../src/coherence/orphan.rs | 2 +- compiler/rustc_hir_analysis/src/collect.rs | 6 +- .../src/collect/generics_of.rs | 6 +- .../src/collect/predicates_of.rs | 6 +- .../src/collect/resolve_bound_vars.rs | 12 +- compiler/rustc_hir_pretty/src/lib.rs | 38 +++---- compiler/rustc_hir_typeck/src/_match.rs | 6 +- compiler/rustc_hir_typeck/src/callee.rs | 2 +- compiler/rustc_hir_typeck/src/cast.rs | 4 +- compiler/rustc_hir_typeck/src/check.rs | 8 +- compiler/rustc_hir_typeck/src/closure.rs | 6 +- compiler/rustc_hir_typeck/src/coercion.rs | 12 +- compiler/rustc_hir_typeck/src/demand.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 76 ++++++------- .../rustc_hir_typeck/src/expr_use_visitor.rs | 20 ++-- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 12 +- .../src/fn_ctxt/adjust_fulfillment_errors.rs | 2 +- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 22 ++-- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 4 +- .../src/fn_ctxt/suggestions.rs | 26 ++--- .../rustc_hir_typeck/src/gather_locals.rs | 2 +- compiler/rustc_hir_typeck/src/lib.rs | 2 +- .../src/mem_categorization.rs | 14 +-- .../rustc_hir_typeck/src/method/confirm.rs | 12 +- compiler/rustc_hir_typeck/src/method/probe.rs | 4 +- .../rustc_hir_typeck/src/method/suggest.rs | 20 ++-- compiler/rustc_hir_typeck/src/pat.rs | 2 +- compiler/rustc_hir_typeck/src/place_op.rs | 6 +- .../rustc_incremental/src/assert_dep_graph.rs | 8 +- .../src/persist/dirty_clean.rs | 6 +- compiler/rustc_incremental/src/persist/fs.rs | 8 +- .../rustc_incremental/src/persist/load.rs | 2 +- .../src/persist/work_product.rs | 2 +- .../src/infer/canonical/query_response.rs | 2 +- .../src/infer/error_reporting/mod.rs | 10 +- .../infer/error_reporting/need_type_info.rs | 2 +- .../nice_region_error/find_anon_type.rs | 2 +- .../mismatched_static_lifetime.rs | 2 +- .../nice_region_error/static_impl_trait.rs | 6 +- .../src/infer/error_reporting/note.rs | 2 +- .../src/infer/error_reporting/suggest.rs | 6 +- .../rustc_infer/src/infer/opaque_types.rs | 8 +- .../src/infer/outlives/components.rs | 4 +- .../src/infer/outlives/obligations.rs | 4 +- .../infer/region_constraints/leak_check.rs | 2 +- compiler/rustc_interface/src/passes.rs | 20 ++-- compiler/rustc_interface/src/queries.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 34 +++--- compiler/rustc_lint/src/context.rs | 20 ++-- compiler/rustc_lint/src/early.rs | 2 +- compiler/rustc_lint/src/expect.rs | 2 +- .../src/for_loops_over_fallibles.rs | 2 +- compiler/rustc_lint/src/internal.rs | 2 +- compiler/rustc_lint/src/late.rs | 12 +- compiler/rustc_lint/src/levels.rs | 16 +-- compiler/rustc_lint/src/lints.rs | 2 +- compiler/rustc_lint/src/non_ascii_idents.rs | 2 +- compiler/rustc_lint/src/nonstandard_style.rs | 6 +- .../src/opaque_hidden_inferred_bound.rs | 2 +- compiler/rustc_lint/src/pass_by_value.rs | 2 +- compiler/rustc_lint/src/types.rs | 26 ++--- compiler/rustc_lint/src/unused.rs | 16 +-- compiler/rustc_metadata/src/creader.rs | 6 +- compiler/rustc_metadata/src/fs.rs | 2 +- compiler/rustc_metadata/src/locator.rs | 2 +- .../src/rmeta/decoder/cstore_impl.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 22 ++-- compiler/rustc_metadata/src/rmeta/table.rs | 4 +- compiler/rustc_middle/src/hir/map/mod.rs | 12 +- compiler/rustc_middle/src/middle/region.rs | 2 +- compiler/rustc_middle/src/mir/consts.rs | 2 +- compiler/rustc_middle/src/mir/mod.rs | 2 +- compiler/rustc_middle/src/mir/spanview.rs | 6 +- compiler/rustc_middle/src/mir/statement.rs | 2 +- compiler/rustc_middle/src/mir/tcx.rs | 6 +- .../rustc_middle/src/query/on_disk_cache.rs | 11 +- compiler/rustc_middle/src/thir/visit.rs | 4 +- compiler/rustc_middle/src/traits/mod.rs | 2 +- compiler/rustc_middle/src/ty/adt.rs | 4 +- compiler/rustc_middle/src/ty/codec.rs | 2 +- compiler/rustc_middle/src/ty/consts.rs | 8 +- compiler/rustc_middle/src/ty/error.rs | 4 +- compiler/rustc_middle/src/ty/generic_args.rs | 2 +- compiler/rustc_middle/src/ty/generics.rs | 2 +- compiler/rustc_middle/src/ty/impls_ty.rs | 2 +- compiler/rustc_middle/src/ty/layout.rs | 4 +- compiler/rustc_middle/src/ty/mod.rs | 8 +- compiler/rustc_middle/src/ty/print/mod.rs | 2 +- compiler/rustc_middle/src/ty/print/pretty.rs | 16 +-- compiler/rustc_middle/src/ty/relate.rs | 2 +- compiler/rustc_middle/src/ty/sty.rs | 8 +- .../rustc_middle/src/ty/typeck_results.rs | 2 +- compiler/rustc_mir_build/src/build/block.rs | 6 +- .../rustc_mir_build/src/build/custom/mod.rs | 2 +- .../src/build/expr/as_place.rs | 4 +- .../rustc_mir_build/src/build/matches/mod.rs | 14 +-- .../src/build/matches/simplify.rs | 2 +- .../rustc_mir_build/src/build/matches/test.rs | 2 +- compiler/rustc_mir_build/src/build/mod.rs | 6 +- compiler/rustc_mir_build/src/build/scope.rs | 2 +- .../rustc_mir_build/src/check_unsafety.rs | 2 +- compiler/rustc_mir_build/src/thir/cx/block.rs | 4 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 89 +++++++-------- compiler/rustc_mir_build/src/thir/cx/mod.rs | 4 +- .../src/thir/pattern/check_match.rs | 2 +- .../src/thir/pattern/deconstruct_pat.rs | 6 +- .../rustc_mir_build/src/thir/pattern/mod.rs | 16 +-- .../src/thir/pattern/usefulness.rs | 4 +- .../rustc_mir_dataflow/src/elaborate_drops.rs | 14 +-- .../src/framework/direction.rs | 2 +- .../src/framework/engine.rs | 2 +- .../src/framework/lattice.rs | 2 +- .../src/impls/initialized.rs | 4 +- compiler/rustc_mir_dataflow/src/rustc_peek.rs | 2 +- .../src/check_const_item_mutation.rs | 11 +- .../src/check_packed_ref.rs | 2 +- .../rustc_mir_transform/src/check_unsafety.rs | 2 +- .../rustc_mir_transform/src/const_prop.rs | 2 +- .../src/const_prop_lint.rs | 4 +- compiler/rustc_mir_transform/src/copy_prop.rs | 4 +- compiler/rustc_mir_transform/src/coroutine.rs | 16 +-- .../src/coverage/counters.rs | 6 +- .../rustc_mir_transform/src/coverage/graph.rs | 2 +- .../rustc_mir_transform/src/coverage/mod.rs | 4 +- .../rustc_mir_transform/src/ctfe_limit.rs | 2 +- .../src/dataflow_const_prop.rs | 2 +- .../src/elaborate_drops.rs | 4 +- .../src/function_item_references.rs | 6 +- compiler/rustc_mir_transform/src/inline.rs | 2 +- .../rustc_mir_transform/src/instsimplify.rs | 7 +- .../rustc_mir_transform/src/jump_threading.rs | 4 +- compiler/rustc_mir_transform/src/lib.rs | 4 +- .../rustc_mir_transform/src/pass_manager.rs | 6 +- .../src/remove_uninit_drops.rs | 2 +- compiler/rustc_mir_transform/src/simplify.rs | 2 +- compiler/rustc_mir_transform/src/sroa.rs | 2 +- .../src/uninhabited_enum_branching.rs | 2 +- compiler/rustc_monomorphize/src/collector.rs | 14 +-- .../rustc_monomorphize/src/partitioning.rs | 6 +- compiler/rustc_parse/src/lexer/mod.rs | 6 +- compiler/rustc_parse/src/lexer/tokentrees.rs | 6 +- .../rustc_parse/src/parser/diagnostics.rs | 8 +- compiler/rustc_parse/src/parser/expr.rs | 12 +- compiler/rustc_parse/src/parser/item.rs | 2 +- compiler/rustc_parse/src/parser/pat.rs | 4 +- compiler/rustc_parse/src/validate_attr.rs | 2 +- compiler/rustc_passes/src/check_attr.rs | 52 ++++----- compiler/rustc_passes/src/check_const.rs | 2 +- compiler/rustc_passes/src/dead.rs | 16 +-- compiler/rustc_passes/src/entry.rs | 2 +- compiler/rustc_passes/src/lang_items.rs | 2 +- compiler/rustc_passes/src/liveness.rs | 106 +++++++++--------- compiler/rustc_passes/src/loops.rs | 12 +- compiler/rustc_passes/src/naked_functions.rs | 6 +- compiler/rustc_passes/src/stability.rs | 10 +- compiler/rustc_privacy/src/lib.rs | 8 +- compiler/rustc_query_impl/src/plumbing.rs | 2 +- .../rustc_query_system/src/dep_graph/graph.rs | 2 +- .../rustc_query_system/src/query/plumbing.rs | 10 +- .../rustc_resolve/src/build_reduced_graph.rs | 2 +- compiler/rustc_resolve/src/diagnostics.rs | 4 +- .../src/effective_visibilities.rs | 2 +- compiler/rustc_resolve/src/imports.rs | 4 +- compiler/rustc_resolve/src/late.rs | 24 ++-- .../rustc_resolve/src/late/diagnostics.rs | 6 +- compiler/rustc_resolve/src/macros.rs | 6 +- compiler/rustc_resolve/src/rustdoc.rs | 2 +- compiler/rustc_session/src/config.rs | 2 +- compiler/rustc_session/src/session.rs | 2 +- .../rustc_smir/src/rustc_internal/internal.rs | 4 +- .../src/typeid/typeid_itanium_cxx_abi.rs | 6 +- .../src/solve/assembly/mod.rs | 2 +- .../src/solve/assembly/structural_traits.rs | 6 +- .../src/solve/inspect/analyse.rs | 2 +- .../src/traits/auto_trait.rs | 2 +- .../src/traits/engine.rs | 4 +- .../traits/error_reporting/infer_ctxt_ext.rs | 7 +- .../error_reporting/on_unimplemented.rs | 4 +- .../src/traits/error_reporting/suggestions.rs | 36 +++--- .../error_reporting/type_err_ctxt_ext.rs | 18 +-- .../src/traits/object_safety.rs | 2 +- .../src/traits/project.rs | 10 +- .../src/traits/query/dropck_outlives.rs | 4 +- .../src/traits/query/evaluate_obligation.rs | 2 +- .../src/traits/select/candidate_assembly.rs | 7 +- .../src/traits/select/confirmation.rs | 10 +- .../src/traits/select/mod.rs | 14 +-- .../src/traits/specialize/mod.rs | 31 +++-- .../rustc_trait_selection/src/traits/wf.rs | 2 +- .../rustc_traits/src/evaluate_obligation.rs | 2 +- compiler/rustc_ty_utils/src/assoc.rs | 8 +- compiler/rustc_ty_utils/src/consts.rs | 2 +- compiler/rustc_ty_utils/src/layout.rs | 4 +- compiler/rustc_ty_utils/src/ty.rs | 4 +- compiler/stable_mir/src/mir/pretty.rs | 4 +- compiler/stable_mir/src/mir/visit.rs | 2 +- compiler/stable_mir/src/ty.rs | 2 +- 304 files changed, 1101 insertions(+), 1174 deletions(-) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 996fd5bbecfc..815edcc0dc4b 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -111,8 +111,8 @@ pub trait LayoutCalculator { alt_tail_space, layout.fields.count(), prefer_alt_layout, - format_field_niches(&layout, &fields, &dl), - format_field_niches(&alt_layout, &fields, &dl), + format_field_niches(layout, fields, dl), + format_field_niches(&alt_layout, fields, dl), ); if prefer_alt_layout { @@ -1025,7 +1025,7 @@ fn univariant< // At the bottom of this function, we invert `inverse_memory_index` to // produce `memory_index` (see `invert_mapping`). let mut sized = true; - let mut offsets = IndexVec::from_elem(Size::ZERO, &fields); + let mut offsets = IndexVec::from_elem(Size::ZERO, fields); let mut offset = Size::ZERO; let mut largest_niche = None; let mut largest_niche_available = 0; diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 152ef4bcbfd3..851ab46345fd 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -391,7 +391,7 @@ impl MetaItemKind { MetaItemKind::name_value_from_tokens(&mut inner_tokens.trees()) } Some(TokenTree::Token(token, _)) => { - MetaItemLit::from_token(&token).map(MetaItemKind::NameValue) + MetaItemLit::from_token(token).map(MetaItemKind::NameValue) } _ => None, } diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 2c13e1523f15..d44c585a07d3 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -959,7 +959,7 @@ impl<'hir> LoweringContext<'_, 'hir> { e }); let coroutine_option = - this.coroutine_movability_for_fn(&decl, fn_decl_span, coroutine_kind, movability); + this.coroutine_movability_for_fn(decl, fn_decl_span, coroutine_kind, movability); this.current_item = prev; (body_id, coroutine_option) }); @@ -1057,7 +1057,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let body_id = this.lower_fn_body(&outer_decl, |this| { let async_ret_ty = if let FnRetTy::Ty(ty) = &decl.output { let itctx = ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock); - Some(hir::FnRetTy::Return(this.lower_ty(&ty, &itctx))) + Some(hir::FnRetTy::Return(this.lower_ty(ty, &itctx))) } else { None }; @@ -1156,7 +1156,7 @@ impl<'hir> LoweringContext<'_, 'hir> { .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter())); // Wrap everything in a block. - hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None) + hir::ExprKind::Block(self.block_all(whole_span, stmts, None), None) } /// If the given expression is a path to a tuple struct, returns that path. @@ -1413,7 +1413,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let fields = self.arena.alloc_from_iter( e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map( |(s, e)| { - let expr = self.lower_expr(&e); + let expr = self.lower_expr(e); let ident = Ident::new(s, self.lower_span(e.span)); self.expr_field(ident, expr, e.span) }, diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index c7d0719e71ab..b6202be4f52a 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -338,8 +338,8 @@ fn make_format_spec<'hir>( | ((debug_hex == Some(FormatDebugHex::Lower)) as u32) << 4 | ((debug_hex == Some(FormatDebugHex::Upper)) as u32) << 5; let flags = ctx.expr_u32(sp, flags); - let precision = make_count(ctx, sp, &precision, argmap); - let width = make_count(ctx, sp, &width, argmap); + let precision = make_count(ctx, sp, precision, argmap); + let width = make_count(ctx, sp, width, argmap); let format_placeholder_new = ctx.arena.alloc(ctx.expr_lang_item_type_relative( sp, hir::LangItem::FormatPlaceholder, diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index eff362f3ff0c..33e15d386c88 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -47,7 +47,7 @@ pub(super) fn index_hir<'hir>( match item { OwnerNode::Crate(citem) => { - collector.visit_mod(&citem, citem.spans.inner_span, hir::CRATE_HIR_ID) + collector.visit_mod(citem, citem.spans.inner_span, hir::CRATE_HIR_ID) } OwnerNode::Item(item) => collector.visit_item(item), OwnerNode::TraitItem(item) => collector.visit_trait_item(item), diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 9a70e6d7c4a1..c4c08096b8bb 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -276,19 +276,14 @@ impl<'hir> LoweringContext<'_, 'hir> { // only cares about the input argument patterns in the function // declaration (decl), not the return types. let asyncness = header.asyncness; - let body_id = this.lower_maybe_async_body( - span, - hir_id, - &decl, - asyncness, - body.as_deref(), - ); + let body_id = + this.lower_maybe_async_body(span, hir_id, decl, asyncness, body.as_deref()); let itctx = ImplTraitContext::Universal; let (generics, decl) = this.lower_generics(generics, header.constness, id, &itctx, |this| { let ret_id = asyncness.opt_return_id(); - this.lower_fn_decl(&decl, id, *fn_sig_span, FnDeclKind::Fn, ret_id) + this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, ret_id) }); let sig = hir::FnSig { decl, @@ -744,7 +739,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let (generics, kind, has_default) = match &i.kind { AssocItemKind::Const(box ConstItem { generics, ty, expr, .. }) => { let (generics, kind) = self.lower_generics( - &generics, + generics, Const::No, i.id, &ImplTraitContext::Disallowed(ImplTraitPosition::Generic), @@ -775,7 +770,7 @@ impl<'hir> LoweringContext<'_, 'hir> { AssocItemKind::Fn(box Fn { sig, generics, body: Some(body), .. }) => { let asyncness = sig.header.asyncness; let body_id = - self.lower_maybe_async_body(i.span, hir_id, &sig.decl, asyncness, Some(&body)); + self.lower_maybe_async_body(i.span, hir_id, &sig.decl, asyncness, Some(body)); let (generics, sig) = self.lower_method_sig( generics, sig, @@ -857,7 +852,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let (generics, kind) = match &i.kind { AssocItemKind::Const(box ConstItem { generics, ty, expr, .. }) => self.lower_generics( - &generics, + generics, Const::No, i.id, &ImplTraitContext::Disallowed(ImplTraitPosition::Generic), diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 3db9d0b31e0e..e9554f107765 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1157,7 +1157,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { itctx: &ImplTraitContext, ) -> hir::GenericArg<'hir> { match arg { - ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)), + ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(lt)), ast::GenericArg::Type(ty) => { match &ty.kind { TyKind::Infer if self.tcx.features().generic_arg_infer => { @@ -1221,10 +1221,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } _ => {} } - GenericArg::Type(self.lower_ty(&ty, itctx)) + GenericArg::Type(self.lower_ty(ty, itctx)) } ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg { - value: self.lower_anon_const(&ct), + value: self.lower_anon_const(ct), span: self.lower_span(ct.value.span), is_desugared_from_effects: false, }), @@ -1267,7 +1267,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let lifetime_bound = this.elided_dyn_bound(t.span); (bounds, lifetime_bound) }); - let kind = hir::TyKind::TraitObject(bounds, &lifetime_bound, TraitObjectSyntax::None); + let kind = hir::TyKind::TraitObject(bounds, lifetime_bound, TraitObjectSyntax::None); return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() }; } @@ -1551,7 +1551,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` // example, we only need to duplicate lifetimes that appear in the // bounds, since those are the only ones that are captured by the opaque. - lifetime_collector::lifetimes_in_bounds(&self.resolver, bounds) + lifetime_collector::lifetimes_in_bounds(self.resolver, bounds) } } hir::OpaqueTyOrigin::AsyncFn(..) => { @@ -2067,10 +2067,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { (hir::ParamName::Plain(self.lower_ident(param.ident)), kind) } GenericParamKind::Const { ty, kw_span: _, default } => { - let ty = self.lower_ty( - &ty, - &ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault), - ); + let ty = self + .lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault)); let default = default.as_ref().map(|def| self.lower_anon_const(def)); ( hir::ParamName::Plain(self.lower_ident(param.ident)), diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 899f92a99582..8050f5826aaf 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -372,10 +372,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // ``` FnRetTy::Ty(ty) if matches!(itctx, ImplTraitContext::ReturnPositionOpaqueTy { .. }) => { if self.tcx.features().impl_trait_in_fn_trait_return { - self.lower_ty(&ty, itctx) + self.lower_ty(ty, itctx) } else { self.lower_ty( - &ty, + ty, &ImplTraitContext::FeatureGated( ImplTraitPosition::FnTraitReturn, sym::impl_trait_in_fn_trait_return, @@ -384,7 +384,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } FnRetTy::Ty(ty) => { - self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn)) + self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn)) } FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])), }; diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index f73d791db49e..1a45c8eb1a53 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -221,7 +221,7 @@ impl<'a> AstValidator<'a> { } fn err_handler(&self) -> &rustc_errors::Handler { - &self.session.diagnostic() + self.session.diagnostic() } fn check_lifetime(&self, ident: Ident) { @@ -622,7 +622,7 @@ impl<'a> AstValidator<'a> { data: data.span, constraint_spans: errors::EmptyLabelManySpans(constraint_spans), arg_spans2: errors::EmptyLabelManySpans(arg_spans), - suggestion: self.correct_generic_order_suggestion(&data), + suggestion: self.correct_generic_order_suggestion(data), constraint_len, args_len, }); @@ -738,7 +738,7 @@ fn validate_generic_param_order( if !bounds.is_empty() { ordered_params += ": "; - ordered_params += &pprust::bounds_to_string(&bounds); + ordered_params += &pprust::bounds_to_string(bounds); } match kind { diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index e1cf0a2589d3..8fb7c7de50c6 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -88,7 +88,7 @@ impl<'a> PostExpansionVisitor<'a> { } } - match abi::is_enabled(&self.features, span, symbol_unescaped.as_str()) { + match abi::is_enabled(self.features, span, symbol_unescaped.as_str()) { Ok(()) => (), Err(abi::AbiDisabled::Unstable { feature, explain }) => { feature_err_issue( @@ -182,7 +182,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { .. }) = attr_info { - gate_alt!(self, has_feature(&self.features), *name, attr.span, *descr); + gate_alt!(self, has_feature(self.features), *name, attr.span, *descr); } // Check unstable flavors of the `#[doc]` attribute. if attr.has_name(sym::doc) { @@ -300,7 +300,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { } ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ty), .. }) => { - self.check_impl_trait(&ty, false) + self.check_impl_trait(ty, false) } _ => {} diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 0962cb1b8d48..e486ab8e3b81 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1078,11 +1078,11 @@ impl<'a> State<'a> { } ast::TyKind::AnonStruct(fields) => { self.head("struct"); - self.print_record_struct_body(&fields, ty.span); + self.print_record_struct_body(fields, ty.span); } ast::TyKind::AnonUnion(fields) => { self.head("union"); - self.print_record_struct_body(&fields, ty.span); + self.print_record_struct_body(fields, ty.span); } ast::TyKind::Paren(typ) => { self.popen(); diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 3393f034bc3b..e94bfd816582 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -368,7 +368,7 @@ impl<'a> State<'a> { self.nbsp(); if !bounds.is_empty() { self.word_nbsp("="); - self.print_type_bounds(&bounds); + self.print_type_bounds(bounds); } self.print_where_clause(&generics.where_clause); self.word(";"); diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index ad92d5855100..7e87d1c31301 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -552,7 +552,7 @@ pub fn cfg_matches( fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) { let gate = find_gated_cfg(|sym| sym == name); if let (Some(feats), Some(gated_cfg)) = (features, gate) { - gate_cfg(&gated_cfg, span, sess, feats); + gate_cfg(gated_cfg, span, sess, feats); } } diff --git a/compiler/rustc_borrowck/src/borrow_set.rs b/compiler/rustc_borrowck/src/borrow_set.rs index 5248a649c349..948af0395371 100644 --- a/compiler/rustc_borrowck/src/borrow_set.rs +++ b/compiler/rustc_borrowck/src/borrow_set.rs @@ -107,7 +107,7 @@ impl LocalsStateAtExit { LocalsStateAtExit::AllAreInvalidated } else { let mut has_storage_dead = HasStorageDead(BitSet::new_empty(body.local_decls.len())); - has_storage_dead.visit_body(&body); + has_storage_dead.visit_body(body); let mut has_storage_dead_or_moved = has_storage_dead.0; for move_out in &move_data.moves { if let Some(index) = move_data.base_local(move_out.path) { @@ -128,7 +128,7 @@ impl<'tcx> BorrowSet<'tcx> { ) -> Self { let mut visitor = GatherBorrows { tcx, - body: &body, + body: body, location_map: Default::default(), activation_map: Default::default(), local_map: Default::default(), @@ -140,7 +140,7 @@ impl<'tcx> BorrowSet<'tcx> { ), }; - for (block, block_data) in traversal::preorder(&body) { + for (block, block_data) in traversal::preorder(body) { visitor.visit_basic_block_data(block, block_data); } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 875a71145fa2..a09b24d34227 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -490,7 +490,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let mut spans = vec![]; for init_idx in inits { let init = &self.move_data.inits[*init_idx]; - let span = init.span(&self.body); + let span = init.span(self.body); if !span.is_dummy() { spans.push(span); } @@ -518,7 +518,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let body = map.body(body_id); let mut visitor = ConditionVisitor { spans: &spans, name: &name, errors: vec![] }; - visitor.visit_body(&body); + visitor.visit_body(body); let mut show_assign_sugg = false; let isnt_initialized = if let InitializationRequiringAction::PartialAssignment @@ -614,7 +614,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } let mut visitor = LetVisitor { decl_span, sugg_span: None }; - visitor.visit_body(&body); + visitor.visit_body(body); if let Some(span) = visitor.sugg_span { self.suggest_assign_value(&mut err, moved_place, span); } @@ -779,7 +779,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { return; }; // Try to find predicates on *generic params* that would allow copying `ty` - let ocx = ObligationCtxt::new(&self.infcx); + let ocx = ObligationCtxt::new(self.infcx); let copy_did = tcx.require_lang_item(LangItem::Copy, Some(span)); let cause = ObligationCause::misc(span, self.mir_def_id()); @@ -856,7 +856,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.explain_why_borrow_contains_point(location, borrow, None) .add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, "", @@ -903,7 +903,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.explain_why_borrow_contains_point(location, borrow, None) .add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, "", @@ -1174,7 +1174,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { explanation.add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, first_borrow_desc, @@ -1932,7 +1932,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let place_desc = self.describe_place(borrow.borrowed_place.as_ref()); let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0)); - let explanation = self.explain_why_borrow_contains_point(location, &borrow, kind_place); + let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place); debug!(?place_desc, ?explanation); @@ -2001,14 +2001,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { (Some(name), explanation) => self.report_local_value_does_not_live_long_enough( location, &name, - &borrow, + borrow, drop_span, borrow_spans, explanation, ), (None, explanation) => self.report_temporary_value_does_not_live_long_enough( location, - &borrow, + borrow, drop_span, borrow_spans, proper_span, @@ -2098,7 +2098,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } else { explanation.add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, "", @@ -2119,7 +2119,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { explanation.add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, "", @@ -2180,7 +2180,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { explanation.add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, "", @@ -2365,7 +2365,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } explanation.add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, "", @@ -2842,7 +2842,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.explain_why_borrow_contains_point(location, loan, None).add_explanation_to_diagnostic( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &mut err, "", @@ -3020,7 +3020,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } let mut visitor = FakeReadCauseFinder { place, cause: None }; - visitor.visit_body(&self.body); + visitor.visit_body(self.body); match visitor.cause { Some(FakeReadCause::ForMatchGuard) => Some("match guard"), Some(FakeReadCause::ForIndex) => Some("indexing expression"), diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index 78e9e104bdae..bed3df4809dd 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -422,7 +422,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { kind_place: Option<(WriteKind, Place<'tcx>)>, ) -> BorrowExplanation<'tcx> { let regioncx = &self.regioncx; - let body: &Body<'_> = &self.body; + let body: &Body<'_> = self.body; let tcx = self.infcx.tcx; let borrow_region_vid = borrow.region; diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index c85b2f0a9d75..fca3d6959355 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -354,7 +354,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ty::Adt(def, _) => { let variant = if let Some(idx) = variant_index { assert!(def.is_enum()); - &def.variant(idx) + def.variant(idx) } else { def.non_enum_variant() }; @@ -851,7 +851,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { { let Some((method_did, method_args)) = rustc_middle::util::find_self_call( self.infcx.tcx, - &self.body, + self.body, target_temp, location.block, ) else { @@ -1048,7 +1048,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let ty = moved_place.ty(self.body, tcx).ty; let suggest = match tcx.get_diagnostic_item(sym::IntoIterator) { Some(def_id) => type_known_to_meet_bound_modulo_regions( - &self.infcx, + self.infcx, self.param_env, Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty), def_id, diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index aec1cd504c17..86b761eadf5e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -321,7 +321,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let deref_base = match deref_target_place.projection.as_ref() { [proj_base @ .., ProjectionElem::Deref] => { - PlaceRef { local: deref_target_place.local, projection: &proj_base } + PlaceRef { local: deref_target_place.local, projection: proj_base } } _ => bug!("deref_target_place is not a deref projection"), }; @@ -583,7 +583,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { is_partial_move: false, ty: bind_to.ty, - place: &place_desc, + place: place_desc, span: binding_span, }); } diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 3f702c9d9a09..759d8ef30b1e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -650,14 +650,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &self.upvars, errci.fr, ); let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region( self.infcx.tcx, - &self.body, + self.body, &self.local_names, &self.upvars, errci.outlived_fr, @@ -971,7 +971,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { for found_did in found_dids { let mut traits = vec![]; let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did); - hir_v.visit_ty(&self_ty); + hir_v.visit_ty(self_ty); debug!("trait spans found: {:?}", traits); for span in &traits { let mut multi_span: MultiSpan = vec![*span].into(); diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index fee35485cd7e..5cec966e1b53 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -387,7 +387,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys [implicit_inputs + argument_index]; let (_, span) = self.regioncx.get_argument_name_and_span_for_region( - &self.body, + self.body, &self.local_names, argument_index, ); diff --git a/compiler/rustc_borrowck/src/invalidation.rs b/compiler/rustc_borrowck/src/invalidation.rs index ec6d7b74e61a..a3db101311fa 100644 --- a/compiler/rustc_borrowck/src/invalidation.rs +++ b/compiler/rustc_borrowck/src/invalidation.rs @@ -34,7 +34,7 @@ pub(super) fn generate_invalidates<'tcx>( borrow_set, tcx, location_table, - body: &body, + body: body, dominators, }; ig.visit_body(body); @@ -383,7 +383,7 @@ impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> { (Read(_), BorrowKind::Mut { .. }) => { // Reading from mere reservations of mutable-borrows is OK. - if !is_active(&this.dominators, borrow, location) { + if !is_active(this.dominators, borrow, location) { // If the borrow isn't active yet, reads don't invalidate it assert!(allow_two_phase_borrow(borrow.kind)); return Control::Continue; diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 353e4cf0829d..0bfd2e7e710a 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -219,18 +219,18 @@ fn do_mir_borrowck<'tcx>( let location_table_owned = LocationTable::new(body); let location_table = &location_table_owned; - let move_data = MoveData::gather_moves(&body, tcx, param_env, |_| true); + let move_data = MoveData::gather_moves(body, tcx, param_env, |_| true); let promoted_move_data = promoted .iter_enumerated() - .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env, |_| true))); + .map(|(idx, body)| (idx, MoveData::gather_moves(body, tcx, param_env, |_| true))); let mdpe = MoveDataParamEnv { move_data, param_env }; - let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe) - .into_engine(tcx, &body) + let mut flow_inits = MaybeInitializedPlaces::new(tcx, body, &mdpe) + .into_engine(tcx, body) .pass_name("borrowck") .iterate_to_fixpoint() - .into_results_cursor(&body); + .into_results_cursor(body); let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def).is_fn_or_closure(); let borrow_set = @@ -260,13 +260,13 @@ fn do_mir_borrowck<'tcx>( // Dump MIR results into a file, if that is enabled. This let us // write unit-tests, as well as helping with debugging. - nll::dump_mir_results(&infcx, &body, ®ioncx, &opt_closure_req); + nll::dump_mir_results(&infcx, body, ®ioncx, &opt_closure_req); // We also have a `#[rustc_regions]` annotation that causes us to dump // information. nll::dump_annotation( &infcx, - &body, + body, ®ioncx, &opt_closure_req, &opaque_type_values, @@ -1538,7 +1538,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if places_conflict::borrow_conflicts_with_place( self.infcx.tcx, - &self.body, + self.body, place, borrow.kind, root_place, @@ -2193,7 +2193,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // If this is a mutate access to an immutable local variable with no projections // report the error as an illegal reassignment let init = &self.move_data.inits[init_index]; - let assigned_span = init.span(&self.body); + let assigned_span = init.span(self.body); self.report_illegal_reassignment(location, (place, span), assigned_span, place); } else { self.report_mutability_error(place, span, the_place_err, error_access, location) diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index 0ea4401a8784..08db3a62ece9 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -179,7 +179,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>( let universal_regions = Rc::new(universal_regions); - let elements = &Rc::new(RegionValueElements::new(&body)); + let elements = &Rc::new(RegionValueElements::new(body)); // Run the MIR type-checker. let MirTypeckResults { @@ -206,7 +206,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>( if let Some(all_facts) = &mut all_facts { let _prof_timer = infcx.tcx.prof.generic_activity("polonius_fact_generation"); all_facts.universal_region.extend(universal_regions.universal_regions()); - populate_polonius_move_facts(all_facts, move_data, location_table, &body); + populate_polonius_move_facts(all_facts, move_data, location_table, body); // Emit universal regions facts, and their relations, for Polonius. // @@ -263,7 +263,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>( &mut liveness_constraints, &mut all_facts, location_table, - &body, + body, borrow_set, ); @@ -302,7 +302,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>( let algorithm = Algorithm::from_str(&algorithm).unwrap(); debug!("compute_regions: using polonius algorithm {:?}", algorithm); let _prof_timer = infcx.tcx.prof.generic_activity("polonius_analysis"); - Some(Rc::new(Output::compute(&all_facts, algorithm, false))) + Some(Rc::new(Output::compute(all_facts, algorithm, false))) } else { None } @@ -310,7 +310,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>( // Solve the region constraints. let (closure_region_requirements, nll_errors) = - regioncx.solve(infcx, param_env, &body, polonius_output.clone()); + regioncx.solve(infcx, param_env, body, polonius_output.clone()); if !nll_errors.is_empty() { // Suppress unhelpful extra errors in `infer_opaque_types`. @@ -320,7 +320,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>( )); } - let remapped_opaque_tys = regioncx.infer_opaque_types(&infcx, opaque_type_values); + let remapped_opaque_tys = regioncx.infer_opaque_types(infcx, opaque_type_values); NllOutput { regioncx, diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs index 478eedc26d30..4a76d877af0f 100644 --- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs +++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs @@ -303,7 +303,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> { Locations::All(span), span, ConstraintCategory::Internal, - &mut self.constraints, + self.constraints, ) .convert_all(data); } diff --git a/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs b/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs index a9ca94567878..7433c94a0bcd 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs @@ -80,7 +80,7 @@ impl LocalUseMap { live_locals.iter().for_each(|&local| locals_with_use_data[local] = true); LocalUseMapBuild { local_use_map: &mut local_use_map, elements, locals_with_use_data } - .visit_body(&body); + .visit_body(body); local_use_map } diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index f1ad0ca55ccf..a970dadc4795 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs @@ -42,11 +42,11 @@ pub(super) fn generate<'mir, 'tcx>( let free_regions = regions_that_outlive_free_regions( typeck.infcx.num_region_vars(), - &typeck.borrowck_context.universal_regions, + typeck.borrowck_context.universal_regions, &typeck.borrowck_context.constraints.outlives_constraints, ); let (relevant_live_locals, boring_locals) = - compute_relevant_live_locals(typeck.tcx(), &free_regions, &body); + compute_relevant_live_locals(typeck.tcx(), &free_regions, body); let facts_enabled = use_polonius || AllFacts::enabled(typeck.tcx()); let polonius_drop_used = facts_enabled.then(|| { diff --git a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs index c621df37106b..45f7b07fd5f9 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs @@ -100,7 +100,7 @@ pub(super) fn populate_access_facts<'a, 'tcx>( location_table, move_data, }; - extractor.visit_body(&body); + extractor.visit_body(body); facts.var_dropped_at.extend( dropped_at.iter().map(|&(local, location)| (local, location_table.mid_index(location))), diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs index e616449ccd41..525db88aace8 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs @@ -64,7 +64,7 @@ pub(super) fn trace<'mir, 'tcx>( let num_region_vars = typeck.infcx.num_region_vars(); let graph = constraint_set.graph(num_region_vars); let region_graph = - graph.region_graph(&constraint_set, borrowck_context.universal_regions.fr_static); + graph.region_graph(constraint_set, borrowck_context.universal_regions.fr_static); // Traverse each issuing region's constraints, and record the loan as flowing into the // outlived region. @@ -489,7 +489,7 @@ impl<'tcx> LivenessContext<'_, '_, '_, 'tcx> { } let move_paths = &self.flow_inits.analysis().move_data().move_paths; - move_paths[mpi].find_descendant(&move_paths, |mpi| state.contains(mpi)).is_some() + move_paths[mpi].find_descendant(move_paths, |mpi| state.contains(mpi)).is_some() } /// Returns `true` if the local variable (or some part of it) is initialized in @@ -522,7 +522,7 @@ impl<'tcx> LivenessContext<'_, '_, '_, 'tcx> { Self::make_all_regions_live( self.elements, - &mut self.typeck, + self.typeck, value, live_at, &self.inflowing_loans, @@ -579,13 +579,13 @@ impl<'tcx> LivenessContext<'_, '_, '_, 'tcx> { for &kind in &drop_data.dropck_result.kinds { Self::make_all_regions_live( self.elements, - &mut self.typeck, + self.typeck, kind, live_at, &self.inflowing_loans, ); - polonius::add_drop_of_var_derefs_origin(&mut self.typeck, dropped_local, &kind); + polonius::add_drop_of_var_derefs_origin(self.typeck, dropped_local, &kind); } } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index bb9ce5daba26..fdc710c4b4f3 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -191,11 +191,11 @@ pub(crate) fn type_check<'mir, 'tcx>( checker.check_user_type_annotations(); let mut verifier = TypeVerifier::new(&mut checker, promoted); - verifier.visit_body(&body); + verifier.visit_body(body); checker.typeck_mir(body); - checker.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output); - checker.check_signature_annotation(&body); + checker.equate_inputs_and_outputs(body, universal_regions, &normalized_inputs_and_output); + checker.check_signature_annotation(body); liveness::generate( &mut checker, @@ -389,7 +389,7 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { self.cx.ascribe_user_type( constant.const_.ty(), UserType::TypeOf(uv.def, UserArgs { args: uv.args, user_self_ty: None }), - locations.span(&self.cx.body), + locations.span(self.cx.body), ); } } else if let Some(static_def_id) = constant.check_static_ptr(tcx) { @@ -553,7 +553,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { let all_facts = &mut None; let mut constraints = Default::default(); let mut liveness_constraints = - LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body))); + LivenessValues::new(Rc::new(RegionValueElements::new(promoted_body))); // Don't try to add borrow_region facts for the promoted MIR let mut swap_constraints = |this: &mut Self| { @@ -570,7 +570,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { swap_constraints(self); - self.visit_body(&promoted_body); + self.visit_body(promoted_body); self.cx.typeck_mir(promoted_body); @@ -1127,7 +1127,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { locations, locations.span(self.body), category, - &mut self.borrowck_context.constraints, + self.borrowck_context.constraints, ) .convert_all(data); } @@ -1854,7 +1854,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { for op in ops { self.check_operand(op, location); } - self.check_aggregate_rvalue(&body, rvalue, ak, ops, location) + self.check_aggregate_rvalue(body, rvalue, ak, ops, location) } Rvalue::Repeat(operand, len) => { @@ -2300,7 +2300,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } Rvalue::Ref(region, _borrow_kind, borrowed_place) => { - self.add_reborrow_constraint(&body, location, *region, borrowed_place); + self.add_reborrow_constraint(body, location, *region, borrowed_place); } Rvalue::BinaryOp( @@ -2512,7 +2512,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let tcx = self.infcx.tcx; let field = path_utils::is_upvar_field_projection( tcx, - &self.borrowck_context.upvars, + self.borrowck_context.upvars, borrowed_place.as_ref(), body, ); @@ -2668,13 +2668,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { location.to_locations(), DUMMY_SP, // irrelevant; will be overridden. ConstraintCategory::Boring, // same as above. - &mut self.borrowck_context.constraints, + self.borrowck_context.constraints, ) - .apply_closure_requirements( - &closure_requirements, - def_id.to_def_id(), - args, - ); + .apply_closure_requirements(closure_requirements, def_id.to_def_id(), args); } // Now equate closure args to regions inherited from `typeck_root_def_id`. Fixes #98589. @@ -2714,7 +2710,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { debug!(?body.span); for (local, local_decl) in body.local_decls.iter_enumerated() { - self.check_local(&body, local, local_decl); + self.check_local(body, local, local_decl); } for (block, block_data) in body.basic_blocks.iter_enumerated() { @@ -2727,8 +2723,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { location.statement_index += 1; } - self.check_terminator(&body, block_data.terminator(), location); - self.check_iscleanup(&body, block_data); + self.check_terminator(body, block_data.terminator(), location); + self.check_iscleanup(body, block_data); } } } diff --git a/compiler/rustc_borrowck/src/used_muts.rs b/compiler/rustc_borrowck/src/used_muts.rs index c5991e0bc254..6ac8e1ba7156 100644 --- a/compiler/rustc_borrowck/src/used_muts.rs +++ b/compiler/rustc_borrowck/src/used_muts.rs @@ -35,7 +35,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { never_initialized_mut_locals: &mut never_initialized_mut_locals, mbcx: self, }; - visitor.visit_body(&visitor.mbcx.body); + visitor.visit_body(visitor.mbcx.body); } // Take the union of the existed `used_mut` set with those variables we've found were diff --git a/compiler/rustc_builtin_macros/src/cfg_accessible.rs b/compiler/rustc_builtin_macros/src/cfg_accessible.rs index 37ac09ccdff4..64be8da59028 100644 --- a/compiler/rustc_builtin_macros/src/cfg_accessible.rs +++ b/compiler/rustc_builtin_macros/src/cfg_accessible.rs @@ -47,7 +47,7 @@ impl MultiItemModifier for Expander { let template = AttributeTemplate { list: Some("path"), ..Default::default() }; validate_attr::check_builtin_meta_item( &ecx.sess.parse_sess, - &meta_item, + meta_item, ast::AttrStyle::Outer, sym::cfg_accessible, template, diff --git a/compiler/rustc_builtin_macros/src/cfg_eval.rs b/compiler/rustc_builtin_macros/src/cfg_eval.rs index f826c6e7712d..ca26b7ed8270 100644 --- a/compiler/rustc_builtin_macros/src/cfg_eval.rs +++ b/compiler/rustc_builtin_macros/src/cfg_eval.rs @@ -25,7 +25,7 @@ pub(crate) fn expand( annotatable: Annotatable, ) -> Vec { check_builtin_macro_attribute(ecx, meta_item, sym::cfg_eval); - warn_on_duplicate_attribute(&ecx, &annotatable, sym::cfg_eval); + warn_on_duplicate_attribute(ecx, &annotatable, sym::cfg_eval); vec![cfg_eval(ecx.sess, ecx.ecfg.features, annotatable, ecx.current_expansion.lint_node_id)] } @@ -95,19 +95,19 @@ impl CfgFinder { fn has_cfg_or_cfg_attr(annotatable: &Annotatable) -> bool { let mut finder = CfgFinder { has_cfg_or_cfg_attr: false }; match annotatable { - Annotatable::Item(item) => finder.visit_item(&item), - Annotatable::TraitItem(item) => finder.visit_assoc_item(&item, visit::AssocCtxt::Trait), - Annotatable::ImplItem(item) => finder.visit_assoc_item(&item, visit::AssocCtxt::Impl), - Annotatable::ForeignItem(item) => finder.visit_foreign_item(&item), - Annotatable::Stmt(stmt) => finder.visit_stmt(&stmt), - Annotatable::Expr(expr) => finder.visit_expr(&expr), - Annotatable::Arm(arm) => finder.visit_arm(&arm), - Annotatable::ExprField(field) => finder.visit_expr_field(&field), - Annotatable::PatField(field) => finder.visit_pat_field(&field), - Annotatable::GenericParam(param) => finder.visit_generic_param(¶m), - Annotatable::Param(param) => finder.visit_param(¶m), - Annotatable::FieldDef(field) => finder.visit_field_def(&field), - Annotatable::Variant(variant) => finder.visit_variant(&variant), + Annotatable::Item(item) => finder.visit_item(item), + Annotatable::TraitItem(item) => finder.visit_assoc_item(item, visit::AssocCtxt::Trait), + Annotatable::ImplItem(item) => finder.visit_assoc_item(item, visit::AssocCtxt::Impl), + Annotatable::ForeignItem(item) => finder.visit_foreign_item(item), + Annotatable::Stmt(stmt) => finder.visit_stmt(stmt), + Annotatable::Expr(expr) => finder.visit_expr(expr), + Annotatable::Arm(arm) => finder.visit_arm(arm), + Annotatable::ExprField(field) => finder.visit_expr_field(field), + Annotatable::PatField(field) => finder.visit_pat_field(field), + Annotatable::GenericParam(param) => finder.visit_generic_param(param), + Annotatable::Param(param) => finder.visit_param(param), + Annotatable::FieldDef(field) => finder.visit_field_def(field), + Annotatable::Variant(variant) => finder.visit_variant(variant), Annotatable::Crate(krate) => finder.visit_crate(krate), }; finder.has_cfg_or_cfg_attr diff --git a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs index 7b75d7d84e4f..3b1fde1f0970 100644 --- a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs +++ b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs @@ -11,7 +11,7 @@ pub fn inject(krate: &mut ast::Crate, parse_sess: &ParseSess, attrs: &[String]) for raw_attr in attrs { let mut parser = rustc_parse::new_parser_from_source_str( parse_sess, - FileName::cli_crate_attr_source_code(&raw_attr), + FileName::cli_crate_attr_source_code(raw_attr), raw_attr.clone(), ); diff --git a/compiler/rustc_builtin_macros/src/concat_bytes.rs b/compiler/rustc_builtin_macros/src/concat_bytes.rs index c4f5af384c1a..5499852e1770 100644 --- a/compiler/rustc_builtin_macros/src/concat_bytes.rs +++ b/compiler/rustc_builtin_macros/src/concat_bytes.rs @@ -159,7 +159,7 @@ pub fn expand_concat_bytes( accumulator.push(val); } Ok(ast::LitKind::ByteStr(ref bytes, _)) => { - accumulator.extend_from_slice(&bytes); + accumulator.extend_from_slice(bytes); } _ => { if !has_errors { diff --git a/compiler/rustc_builtin_macros/src/derive.rs b/compiler/rustc_builtin_macros/src/derive.rs index 140853db695a..5a77c3276e2a 100644 --- a/compiler/rustc_builtin_macros/src/derive.rs +++ b/compiler/rustc_builtin_macros/src/derive.rs @@ -35,7 +35,7 @@ impl MultiItemModifier for Expander { AttributeTemplate { list: Some("Trait1, Trait2, ..."), ..Default::default() }; validate_attr::check_builtin_meta_item( &sess.parse_sess, - &meta_item, + meta_item, ast::AttrStyle::Outer, sym::derive, template, @@ -48,14 +48,14 @@ impl MultiItemModifier for Expander { NestedMetaItem::MetaItem(meta) => Some(meta), NestedMetaItem::Lit(lit) => { // Reject `#[derive("Debug")]`. - report_unexpected_meta_item_lit(sess, &lit); + report_unexpected_meta_item_lit(sess, lit); None } }) .map(|meta| { // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the // paths. - report_path_args(sess, &meta); + report_path_args(sess, meta); meta.path.clone() }) .map(|path| (path, dummy_annotatable(), None, self.0)) diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index aa1ce1b929d0..23502b6eafc6 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -467,7 +467,7 @@ impl<'a> TraitDef<'a> { match item { Annotatable::Item(item) => { let is_packed = item.attrs.iter().any(|attr| { - for r in attr::find_repr_attrs(&cx.sess, attr) { + for r in attr::find_repr_attrs(cx.sess, attr) { if let attr::ReprPacked(_) = r { return true; } @@ -478,7 +478,7 @@ impl<'a> TraitDef<'a> { let newitem = match &item.kind { ast::ItemKind::Struct(struct_def, generics) => self.expand_struct_def( cx, - &struct_def, + struct_def, item.ident, generics, from_scratch, @@ -496,7 +496,7 @@ impl<'a> TraitDef<'a> { if self.supports_unions { self.expand_struct_def( cx, - &struct_def, + struct_def, item.ident, generics, from_scratch, diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs index 2d5043112b67..1a45c3279f75 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs @@ -182,7 +182,7 @@ impl Bounds { let params = self .bounds .iter() - .map(|&(name, ref bounds)| mk_ty_param(cx, span, name, &bounds, self_ty, self_generics)) + .map(|&(name, ref bounds)| mk_ty_param(cx, span, name, bounds, self_ty, self_generics)) .collect(); Generics { diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 8a3e15ee24a9..12d12d5bff06 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -547,7 +547,7 @@ fn make_format_args( span: arg_name.span.into(), msg: format!("named argument `{}` is not used by name", arg_name.name).into(), node_id: rustc_ast::CRATE_NODE_ID, - lint_id: LintId::of(&NAMED_ARGUMENTS_USED_POSITIONALLY), + lint_id: LintId::of(NAMED_ARGUMENTS_USED_POSITIONALLY), diagnostic: BuiltinLintDiagnostics::NamedArgumentUsedPositionally { position_sp_to_replace, position_sp_for_msg, @@ -632,8 +632,7 @@ fn report_missing_placeholders( .collect::>(); if !placeholders.is_empty() { - if let Some(mut new_diag) = - report_redundant_format_arguments(ecx, &args, used, placeholders) + if let Some(mut new_diag) = report_redundant_format_arguments(ecx, args, used, placeholders) { diag.cancel(); new_diag.emit(); diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index f7bafa2856e4..7ae4b1b59dcd 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -133,7 +133,7 @@ pub fn expand_include<'cx>( let r = base::parse_expr(&mut self.p)?; if self.p.token != token::Eof { self.p.sess.buffer_lint( - &INCOMPLETE_INCLUDE, + INCOMPLETE_INCLUDE, self.p.token.span, self.node_id, "include macro expected single expression in source", @@ -189,7 +189,7 @@ pub fn expand_include_str( match cx.source_map().load_binary_file(&file) { Ok(bytes) => match std::str::from_utf8(&bytes) { Ok(src) => { - let interned_src = Symbol::intern(&src); + let interned_src = Symbol::intern(src); base::MacEager::expr(cx.expr_str(sp, interned_src)) } Err(_) => { diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 6d55603c7083..c0055380c25f 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -26,7 +26,7 @@ pub fn expand_test_case( anno_item: Annotatable, ) -> Vec { check_builtin_macro_attribute(ecx, meta_item, sym::test_case); - warn_on_duplicate_attribute(&ecx, &anno_item, sym::test_case); + warn_on_duplicate_attribute(ecx, &anno_item, sym::test_case); if !ecx.ecfg.should_test { return vec![]; @@ -79,7 +79,7 @@ pub fn expand_test( item: Annotatable, ) -> Vec { check_builtin_macro_attribute(cx, meta_item, sym::test); - warn_on_duplicate_attribute(&cx, &item, sym::test); + warn_on_duplicate_attribute(cx, &item, sym::test); expand_test_or_bench(cx, attr_sp, item, false) } @@ -90,7 +90,7 @@ pub fn expand_bench( item: Annotatable, ) -> Vec { check_builtin_macro_attribute(cx, meta_item, sym::bench); - warn_on_duplicate_attribute(&cx, &item, sym::bench); + warn_on_duplicate_attribute(cx, &item, sym::bench); expand_test_or_bench(cx, attr_sp, item, true) } @@ -134,9 +134,9 @@ pub fn expand_test_or_bench( // will fail. We shouldn't try to expand in this case because the errors // would be spurious. let check_result = if is_bench { - check_bench_signature(cx, &item, &fn_) + check_bench_signature(cx, &item, fn_) } else { - check_test_signature(cx, &item, &fn_) + check_test_signature(cx, &item, fn_) }; if check_result.is_err() { return if is_stmt { diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index c7999a226c7d..380556c3ca5f 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -60,7 +60,7 @@ pub fn inject( // Do this here so that the test_runner crate attribute gets marked as used // even in non-test builds - let test_runner = get_test_runner(span_diagnostic, &krate); + let test_runner = get_test_runner(span_diagnostic, krate); if sess.is_test_crate() { let panic_strategy = match (panic_strategy, sess.opts.unstable_opts.panic_abort_tests) { @@ -372,7 +372,7 @@ fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> P { let ecx = &cx.ext_cx; let mut tests = cx.test_cases.clone(); - tests.sort_by(|a, b| a.name.as_str().cmp(&b.name.as_str())); + tests.sort_by(|a, b| a.name.as_str().cmp(b.name.as_str())); ecx.expr_array_ref( sp, diff --git a/compiler/rustc_builtin_macros/src/util.rs b/compiler/rustc_builtin_macros/src/util.rs index 9463a1418ce3..eeaf00004e63 100644 --- a/compiler/rustc_builtin_macros/src/util.rs +++ b/compiler/rustc_builtin_macros/src/util.rs @@ -10,7 +10,7 @@ pub fn check_builtin_macro_attribute(ecx: &ExtCtxt<'_>, meta_item: &MetaItem, na let template = AttributeTemplate { word: true, ..Default::default() }; validate_attr::check_builtin_meta_item( &ecx.sess.parse_sess, - &meta_item, + meta_item, AttrStyle::Outer, name, template, diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index a5ffe0650a8a..b5f53f518383 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -493,7 +493,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { PassMode::Cast { cast, pad_i32: _ } => { cast.attrs.apply_attrs_to_callsite( llvm::AttributePlace::ReturnValue, - &bx.cx, + bx.cx, callsite, ); } diff --git a/compiler/rustc_codegen_llvm/src/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index db5c1388ef84..798014d668e2 100644 --- a/compiler/rustc_codegen_llvm/src/allocator.rs +++ b/compiler/rustc_codegen_llvm/src/allocator.rs @@ -67,7 +67,7 @@ pub(crate) unsafe fn codegen( llcx, llmod, "__rust_alloc_error_handler", - &alloc_error_handler_name(alloc_error_handler_kind), + alloc_error_handler_name(alloc_error_handler_kind), &[usize, usize], // size, align None, true, diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index b6c01545f308..92ae59ad3520 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -136,7 +136,7 @@ fn instrument_function_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attr attrs.push(llvm::CreateAttrStringValue( cx.llcx, "instrument-function-entry-inlined", - &mcount_name, + mcount_name, )); } if let Some(options) = &cx.sess().opts.unstable_opts.instrument_xray { @@ -459,7 +459,7 @@ pub fn from_fn_attrs<'ll, 'tcx>( // If this function is an import from the environment but the wasm // import has a specific module/name, apply them here. if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) { - to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", &module)); + to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", module)); let name = codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id())); diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index f33075a88796..cf47c94a81ff 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -68,7 +68,7 @@ impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> { ) -> io::Result<()> { let mut archive = archive.to_path_buf(); if self.sess.target.llvm_target.contains("-apple-macosx") { - if let Some(new_archive) = try_extract_macho_fat_archive(&self.sess, &archive)? { + if let Some(new_archive) = try_extract_macho_fat_archive(self.sess, &archive)? { archive = new_archive } } diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 8d335ff17183..3a8b8e1ad112 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -124,7 +124,7 @@ pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMach let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }; target_machine_factory( - &tcx.sess, + tcx.sess, tcx.backend_optimization_level(()), tcx.global_backend_features(()), )(config) @@ -1106,7 +1106,7 @@ fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, llmod: &llvm::Modu } let raw_stats = - llvm::build_string(|s| unsafe { llvm::LLVMRustModuleInstructionStats(&llmod, s) }) + llvm::build_string(|s| unsafe { llvm::LLVMRustModuleInstructionStats(llmod, s) }) .expect("cannot get module instruction stats"); #[derive(serde::Deserialize)] diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index 0c9f7f195519..e675362ac338 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -62,7 +62,7 @@ pub fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>) -> // exemption for MinGW for backwards compatibility. let llfn = cx.declare_fn( &common::i686_decorated_name( - &dllimport, + dllimport, common::is_mingw_gnu_toolchain(&tcx.sess.target), true, ), diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 307c1264dc1b..b6bc5395bf6b 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -187,7 +187,7 @@ fn check_and_apply_linkage<'ll, 'tcx>( { cx.declare_global( &common::i686_decorated_name( - &dllimport, + dllimport, common::is_mingw_gnu_toolchain(&cx.tcx.sess.target), true, ), diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 274e0aeaaba4..4f540de7ae01 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -176,7 +176,7 @@ impl GlobalFileTable { // compilation directory can be combined with the relative paths // to get absolute paths, if needed. use rustc_session::RemapFileNameExt; - let working_dir: &str = &tcx.sess.opts.working_dir.for_codegen(&tcx.sess).to_string_lossy(); + let working_dir: &str = &tcx.sess.opts.working_dir.for_codegen(tcx.sess).to_string_lossy(); llvm::build_byte_buffer(|buffer| { coverageinfo::write_filenames_section_to_buffer( diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 865bf01c8c1e..cf78fc56b498 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -853,7 +853,7 @@ pub fn build_compile_unit_di_node<'ll, 'tcx>( use rustc_session::RemapFileNameExt; let name_in_debuginfo = name_in_debuginfo.to_string_lossy(); - let work_dir = tcx.sess.opts.working_dir.for_codegen(&tcx.sess).to_string_lossy(); + let work_dir = tcx.sess.opts.working_dir.for_codegen(tcx.sess).to_string_lossy(); let flags = "\0"; let output_filenames = tcx.output_filenames(()); let split_name = if tcx.sess.target_can_use_split_dwarf() { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs index ca7bfbeac25c..7ef185250a38 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs @@ -715,7 +715,7 @@ fn build_union_fields_for_direct_tag_coroutine<'ll, 'tcx>( coroutine_type_and_layout, coroutine_type_di_node, coroutine_layout, - &common_upvar_names, + common_upvar_names, ); let span = coroutine_layout.variant_source_info[variant_index].span; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs index 7eff52b857f8..130ca2727e4c 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs @@ -197,7 +197,7 @@ pub(super) fn build_coroutine_di_node<'ll, 'tcx>( coroutine_type_and_layout, coroutine_type_di_node, coroutine_layout, - &common_upvar_names, + common_upvar_names, ), source_info, } diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index c86bf81fc131..156c9b764170 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -537,8 +537,7 @@ pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec AssertModuleSource<'tcx> { self.cgu_reuse_tracker.set_expectation( cgu_name, - &user_path, + user_path, attr.span, expected_reuse, comp_kind, diff --git a/compiler/rustc_codegen_ssa/src/back/archive.rs b/compiler/rustc_codegen_ssa/src/back/archive.rs index 1c464b3eca49..4dc28adf336d 100644 --- a/compiler/rustc_codegen_ssa/src/back/archive.rs +++ b/compiler/rustc_codegen_ssa/src/back/archive.rs @@ -175,8 +175,7 @@ impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> { ) -> io::Result<()> { let mut archive_path = archive_path.to_path_buf(); if self.sess.target.llvm_target.contains("-apple-macosx") { - if let Some(new_archive_path) = - try_extract_macho_fat_archive(&self.sess, &archive_path)? + if let Some(new_archive_path) = try_extract_macho_fat_archive(self.sess, &archive_path)? { archive_path = new_archive_path } diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 33e8f352cd8a..903563671a62 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -277,7 +277,7 @@ pub fn each_linked_rlib( let crate_name = info.crate_name[&cnum]; let used_crate_source = &info.used_crate_source[&cnum]; if let Some((path, _)) = &used_crate_source.rlib { - f(cnum, &path); + f(cnum, path); } else { if used_crate_source.rmeta.is_some() { return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name }); @@ -524,7 +524,7 @@ fn link_staticlib<'a>( && !ignored_for_lto(sess, &codegen_results.crate_info, cnum); let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter(); - let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, &lib)); + let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib)); let relevant_libs: FxHashSet<_> = relevant.filter_map(|lib| lib.filename).collect(); let bundled_libs: FxHashSet<_> = native_libs.filter_map(|lib| lib.filename).collect(); @@ -689,7 +689,7 @@ fn link_dwarf_object<'a>( // Adding an executable is primarily done to make `thorin` check that all the referenced // dwarf objects are found in the end. package.add_executable( - &executable_out_filename, + executable_out_filename, thorin::MissingReferencedObjectBehaviour::Skip, )?; @@ -945,7 +945,7 @@ fn link_natively<'a>( { let is_vs_installed = windows_registry::find_vs_version().is_ok(); let has_linker = windows_registry::find_tool( - &sess.opts.target_triple.triple(), + sess.opts.target_triple.triple(), "link.exe", ) .is_some(); @@ -1038,14 +1038,14 @@ fn link_natively<'a>( if sess.target.is_like_osx { match (strip, crate_type) { (Strip::Debuginfo, _) => { - strip_symbols_with_external_utility(sess, "strip", &out_filename, Some("-S")) + strip_symbols_with_external_utility(sess, "strip", out_filename, Some("-S")) } // Per the manpage, `-x` is the maximum safe strip level for dynamic libraries. (#93988) (Strip::Symbols, CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro) => { - strip_symbols_with_external_utility(sess, "strip", &out_filename, Some("-x")) + strip_symbols_with_external_utility(sess, "strip", out_filename, Some("-x")) } (Strip::Symbols, _) => { - strip_symbols_with_external_utility(sess, "strip", &out_filename, None) + strip_symbols_with_external_utility(sess, "strip", out_filename, None) } (Strip::None, _) => {} } @@ -1059,7 +1059,7 @@ fn link_natively<'a>( match strip { // Always preserve the symbol table (-x). Strip::Debuginfo => { - strip_symbols_with_external_utility(sess, stripcmd, &out_filename, Some("-x")) + strip_symbols_with_external_utility(sess, stripcmd, out_filename, Some("-x")) } // Strip::Symbols is handled via the --strip-all linker option. Strip::Symbols => {} @@ -1245,13 +1245,13 @@ fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) { // rpath to the library as well (the rpath should be absolute, see // PR #41352 for details). let filename = format!("rustc{channel}_rt.{name}"); - let path = find_sanitizer_runtime(&sess, &filename); + let path = find_sanitizer_runtime(sess, &filename); let rpath = path.to_str().expect("non-utf8 component in path"); linker.args(&["-Wl,-rpath", "-Xlinker", rpath]); linker.link_dylib(&filename, false, true); } else { let filename = format!("librustc{channel}_rt.{name}.a"); - let path = find_sanitizer_runtime(&sess, &filename).join(&filename); + let path = find_sanitizer_runtime(sess, &filename).join(&filename); linker.link_whole_rlib(&path); } } @@ -1685,7 +1685,7 @@ fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind { // Returns true if linker is located within sysroot fn detect_self_contained_mingw(sess: &Session) -> bool { - let (linker, _) = linker_and_flavor(&sess); + let (linker, _) = linker_and_flavor(sess); // Assume `-C linker=rust-lld` as self-contained mode if linker == Path::new("rust-lld") { return true; @@ -1737,7 +1737,7 @@ fn self_contained_components(sess: &Session, crate_type: CrateType) -> LinkSelfC LinkSelfContainedDefault::InferredForMingw => { sess.host == sess.target && sess.target.vendor != "uwp" - && detect_self_contained_mingw(&sess) + && detect_self_contained_mingw(sess) } } }; @@ -2432,7 +2432,7 @@ fn add_native_libs_from_crate( // If rlib contains native libs as archives, unpack them to tmpdir. let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0; archive_builder_builder - .extract_bundled_libs(rlib, tmpdir, &bundled_libs) + .extract_bundled_libs(rlib, tmpdir, bundled_libs) .unwrap_or_else(|e| sess.emit_fatal(e)); } @@ -2485,7 +2485,7 @@ fn add_native_libs_from_crate( cmd.link_whole_staticlib( name, verbatim, - &search_paths.get_or_init(|| archive_search_paths(sess)), + search_paths.get_or_init(|| archive_search_paths(sess)), ); } else { cmd.link_staticlib(name, verbatim) @@ -2719,7 +2719,7 @@ fn rehome_sysroot_lib_dir<'a>(sess: &'a Session, lib_dir: &Path) -> PathBuf { // already had `fix_windows_verbatim_for_gcc()` applied if needed. sysroot_lib_path } else { - fix_windows_verbatim_for_gcc(&lib_dir) + fix_windows_verbatim_for_gcc(lib_dir) } } @@ -2756,7 +2756,7 @@ fn add_static_crate<'a>( let mut link_upstream = |path: &Path| { let rlib_path = if let Some(dir) = path.parent() { let file_name = path.file_name().expect("rlib path has no file name path component"); - rehome_sysroot_lib_dir(sess, &dir).join(file_name) + rehome_sysroot_lib_dir(sess, dir).join(file_name) } else { fix_windows_verbatim_for_gcc(path) }; @@ -2793,7 +2793,7 @@ fn add_static_crate<'a>( let canonical = f.replace('-', "_"); let is_rust_object = - canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f); + canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f); // If we're performing LTO and this is a rust-generated object // file, then we don't need the object file as it's part of the diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs index 09434513e31e..0cb35021b627 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker.rs @@ -45,7 +45,7 @@ pub fn get_linker<'a>( self_contained: bool, target_cpu: &'a str, ) -> Box { - let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe"); + let msvc_tool = windows_registry::find_tool(sess.opts.target_triple.triple(), "link.exe"); // If our linker looks like a batch script on Windows then to execute this // we'll need to spawn `cmd` explicitly. This is primarily done to handle @@ -78,7 +78,7 @@ pub fn get_linker<'a>( if matches!(flavor, LinkerFlavor::Msvc(..)) && t.vendor == "uwp" { if let Some(ref tool) = msvc_tool { let original_path = tool.path(); - if let Some(ref root_lib_path) = original_path.ancestors().nth(4) { + if let Some(root_lib_path) = original_path.ancestors().nth(4) { let arch = match t.arch.as_ref() { "x86_64" => Some("x64"), "x86" => Some("x86"), @@ -519,7 +519,7 @@ impl<'a> Linker for GccLinker<'a> { // -force_load is the macOS equivalent of --whole-archive, but it // involves passing the full path to the library to link. self.linker_arg("-force_load"); - let lib = find_native_static_library(lib, verbatim, search_path, &self.sess); + let lib = find_native_static_library(lib, verbatim, search_path, self.sess); self.linker_arg(&lib); } } @@ -1590,7 +1590,7 @@ impl<'a> Linker for AixLinker<'a> { fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]) { self.hint_static(); - let lib = find_native_static_library(lib, verbatim, search_path, &self.sess); + let lib = find_native_static_library(lib, verbatim, search_path, self.sess); self.cmd.arg(format!("-bkeepfile:{}", lib.to_str().unwrap())); } diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index 9cd4394108a4..b12ac881100a 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -621,7 +621,7 @@ fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> FxHashMap( let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap(); let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| { - let source_file = in_incr_comp_dir(&incr_comp_session_dir, saved_path); + let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path); debug!( "copying preexisting module `{}` from {:?} to {}", module.name, @@ -914,7 +914,7 @@ fn execute_copy_from_cache_work_item( let object = load_from_incr_comp_dir( cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name)), - &module.source.saved_files.get("o").expect("no saved object file in work product"), + module.source.saved_files.get("o").expect("no saved object file in work product"), ); let dwarf_object = module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| { @@ -924,7 +924,7 @@ fn execute_copy_from_cache_work_item( .expect( "saved dwarf object in work product but `split_dwarf_path` returned `None`", ); - load_from_incr_comp_dir(dwarf_obj_out, &saved_dwarf_object_file) + load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file) }); WorkItemResult::Finished(CompiledModule { diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 23054975548c..1d5205ac67a9 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -148,10 +148,9 @@ pub fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( (&ty::Array(_, len), &ty::Slice(_)) => { cx.const_usize(len.eval_target_usize(cx.tcx(), ty::ParamEnv::reveal_all())) } - ( - &ty::Dynamic(ref data_a, _, src_dyn_kind), - &ty::Dynamic(ref data_b, _, target_dyn_kind), - ) if src_dyn_kind == target_dyn_kind => { + (&ty::Dynamic(data_a, _, src_dyn_kind), &ty::Dynamic(data_b, _, target_dyn_kind)) + if src_dyn_kind == target_dyn_kind => + { let old_info = old_info.expect("unsized_info: missing old info for trait upcasting coercion"); if data_a.principal_def_id() == data_b.principal_def_id() { @@ -458,8 +457,8 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx.set_frame_pointer_type(llfn); cx.apply_target_cpu_attr(llfn); - let llbb = Bx::append_block(&cx, llfn, "top"); - let mut bx = Bx::build(&cx, llbb); + let llbb = Bx::append_block(cx, llfn, "top"); + let mut bx = Bx::build(cx, llbb); bx.insert_reference_to_gdb_debug_scripts_section_global(); @@ -685,7 +684,7 @@ pub fn codegen_crate( // Calculate the CGU reuse let cgu_reuse = tcx.sess.time("find_cgu_reuse", || { - codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect::>() + codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::>() }); crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| { diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 2e0840f2d1bc..f6ae4db62f94 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -477,9 +477,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { ) .emit(); InlineAttr::None - } else if list_contains_name(&items, sym::always) { + } else if list_contains_name(items, sym::always) { InlineAttr::Always - } else if list_contains_name(&items, sym::never) { + } else if list_contains_name(items, sym::never) { InlineAttr::Never } else { struct_span_err!( @@ -514,9 +514,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { if items.len() != 1 { err(attr.span, "expected one argument"); OptimizeAttr::None - } else if list_contains_name(&items, sym::size) { + } else if list_contains_name(items, sym::size) { OptimizeAttr::Size - } else if list_contains_name(&items, sym::speed) { + } else if list_contains_name(items, sym::speed) { OptimizeAttr::Speed } else { err(items[0].span(), "invalid argument"); diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 3c7e8873b4d0..839cc4dabe3b 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -216,7 +216,7 @@ fn push_debuginfo_type_name<'tcx>( output.push(']'); } } - ty::Dynamic(ref trait_data, ..) => { + ty::Dynamic(trait_data, ..) => { let auto_traits: SmallVec<[DefId; 4]> = trait_data.auto_traits().collect(); let has_enclosing_parens = if cpp_like_debuginfo { diff --git a/compiler/rustc_codegen_ssa/src/mir/analyze.rs b/compiler/rustc_codegen_ssa/src/mir/analyze.rs index ed859cb20de9..c1de9b76fe73 100644 --- a/compiler/rustc_codegen_ssa/src/mir/analyze.rs +++ b/compiler/rustc_codegen_ssa/src/mir/analyze.rs @@ -42,7 +42,7 @@ pub fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( // If there exists a local definition that dominates all uses of that local, // the definition should be visited first. Traverse blocks in an order that // is a topological sort of dominance partial order. - for (bb, data) in traversal::reverse_postorder(&mir) { + for (bb, data) in traversal::reverse_postorder(mir) { analyzer.visit_basic_block_data(bb, data); } @@ -202,7 +202,7 @@ impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx> ) => match &mut self.locals[local] { LocalKind::ZST => {} LocalKind::Memory => {} - LocalKind::SSA(def) if def.dominates(location, &self.dominators) => {} + LocalKind::SSA(def) if def.dominates(location, self.dominators) => {} // Reads from uninitialized variables (e.g., in dead code, after // optimizations) require locals to be in (uninitialized) memory. // N.B., there can be uninitialized reads of a local visited after diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 3d2d8f8b5099..a1662f25e149 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -47,7 +47,7 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { &self, fx: &'b mut FunctionCx<'a, 'tcx, Bx>, ) -> Option<&'b Bx::Funclet> { - let cleanup_kinds = (&fx.cleanup_kinds).as_ref()?; + let cleanup_kinds = fx.cleanup_kinds.as_ref()?; let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?; // If `landing_pad_for` hasn't been called yet to create the `Funclet`, // it has to be now. This may not seem necessary, as RPO should lead @@ -161,7 +161,7 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { ) -> MergingSucc { // If there is a cleanup block and the function we're calling can unwind, then // do an invoke, otherwise do a call. - let fn_ty = bx.fn_decl_backend_type(&fn_abi); + let fn_ty = bx.fn_decl_backend_type(fn_abi); let fn_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() { Some(bx.tcx().codegen_fn_attrs(fx.instance.def_id())) @@ -204,9 +204,9 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { let invokeret = bx.invoke( fn_ty, fn_attrs, - Some(&fn_abi), + Some(fn_abi), fn_ptr, - &llargs, + llargs, ret_llbb, unwind_block, self.funclet(fx), @@ -225,7 +225,7 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { } MergingSucc::False } else { - let llret = bx.call(fn_ty, fn_attrs, Some(&fn_abi), fn_ptr, &llargs, self.funclet(fx)); + let llret = bx.call(fn_ty, fn_attrs, Some(fn_abi), fn_ptr, llargs, self.funclet(fx)); if fx.mir[self.bb].is_cleanup { bx.apply_attrs_to_cleanup_callsite(llret); } @@ -273,7 +273,7 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { bx.codegen_inline_asm( template, - &operands, + operands, options, line_spans, instance, @@ -281,7 +281,7 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { ); MergingSucc::False } else { - bx.codegen_inline_asm(template, &operands, options, line_spans, instance, None); + bx.codegen_inline_asm(template, operands, options, line_spans, instance, None); if let Some(target) = destination { self.funclet_br(fx, bx, target, mergeable_succ) @@ -318,7 +318,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { discr: &mir::Operand<'tcx>, targets: &SwitchTargets, ) { - let discr = self.codegen_operand(bx, &discr); + let discr = self.codegen_operand(bx, discr); let switch_ty = discr.layout.ty; let mut target_iter = targets.iter(); if target_iter.len() == 1 { @@ -498,7 +498,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { args = &args[..1]; ( meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE) - .get_fn(bx, vtable, ty, &fn_abi), + .get_fn(bx, vtable, ty, fn_abi), fn_abi, ) } @@ -540,7 +540,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { debug!("args' = {:?}", args); ( meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE) - .get_fn(bx, meta.immediate(), ty, &fn_abi), + .get_fn(bx, meta.immediate(), ty, fn_abi), fn_abi, ) } @@ -864,7 +864,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // promotes any complex rvalues to constants. if i == 2 && intrinsic == sym::simd_shuffle { if let mir::Operand::Constant(constant) = arg { - let (llval, ty) = self.simd_shuffle_indices(&bx, constant); + let (llval, ty) = self.simd_shuffle_indices(bx, constant); return OperandRef { val: Immediate(llval), layout: bx.layout_of(ty), @@ -881,7 +881,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { Self::codegen_intrinsic_call( bx, *instance.as_ref().unwrap(), - &fn_abi, + fn_abi, &args, dest, span, @@ -937,7 +937,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx, meta, op.layout.ty, - &fn_abi, + fn_abi, )); llargs.push(data_ptr); continue 'make_args; @@ -948,7 +948,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx, meta, op.layout.ty, - &fn_abi, + fn_abi, )); llargs.push(data_ptr); continue; @@ -975,7 +975,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx, meta.immediate(), op.layout.ty, - &fn_abi, + fn_abi, )); llargs.push(data_ptr.llval); continue; @@ -1587,9 +1587,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span)); let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, reason.lang_item()); - let fn_ty = bx.fn_decl_backend_type(&fn_abi); + let fn_ty = bx.fn_decl_backend_type(fn_abi); - let llret = bx.call(fn_ty, None, Some(&fn_abi), fn_ptr, &[], funclet.as_ref()); + let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref()); bx.apply_attrs_to_cleanup_callsite(llret); bx.unreachable(); @@ -1662,10 +1662,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } } else { - self.codegen_place( - bx, - mir::PlaceRef { local: dest.local, projection: &dest.projection }, - ) + self.codegen_place(bx, mir::PlaceRef { local: dest.local, projection: dest.projection }) }; if fn_ret.is_indirect() { if dest.align < dest.layout.align.abi { @@ -1696,7 +1693,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { match dest { Nothing => (), - Store(dst) => bx.store_arg(&ret_abi, llval, dst), + Store(dst) => bx.store_arg(ret_abi, llval, dst), IndirectOperand(tmp, index) => { let op = bx.load_operand(tmp); tmp.storage_dead(bx); @@ -1708,7 +1705,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let op = if let PassMode::Cast { .. } = ret_abi.mode { let tmp = PlaceRef::alloca(bx, ret_abi.layout); tmp.storage_live(bx); - bx.store_arg(&ret_abi, llval, tmp); + bx.store_arg(ret_abi, llval, tmp); let op = bx.load_operand(tmp); tmp.storage_dead(bx); op diff --git a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs index 0dc30d21c5b4..14915e816ee9 100644 --- a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs @@ -398,7 +398,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let Some(dbg_loc) = self.dbg_loc(var.source_info) else { return }; let DebugInfoOffset { direct_offset, indirect_offsets, result: _ } = - calculate_debuginfo_offset(bx, &var.projection, base.layout); + calculate_debuginfo_offset(bx, var.projection, base.layout); // When targeting MSVC, create extra allocas for arguments instead of pointing multiple // dbg_var_addr() calls into the same alloca with offsets. MSVC uses CodeView records @@ -416,7 +416,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { if should_create_individual_allocas { let DebugInfoOffset { direct_offset: _, indirect_offsets: _, result: place } = - calculate_debuginfo_offset(bx, &var.projection, base); + calculate_debuginfo_offset(bx, var.projection, base); // Create a variable which will be a pointer to the actual value let ptr_ty = Ty::new_ptr( diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index d0b799e087b2..a6fcf1fd38c1 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -168,7 +168,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty()); debug!("fn_abi: {:?}", fn_abi); - let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir); + let debug_context = cx.create_function_debug_context(instance, fn_abi, llfn, mir); let start_llbb = Bx::append_block(cx, llfn, "start"); let mut start_bx = Bx::build(cx, start_llbb); @@ -180,7 +180,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( } let cleanup_kinds = - base::wants_new_eh_instructions(cx.tcx().sess).then(|| analyze::cleanup_kinds(&mir)); + base::wants_new_eh_instructions(cx.tcx().sess).then(|| analyze::cleanup_kinds(mir)); let cached_llbbs: IndexVec> = mir.basic_blocks @@ -261,7 +261,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( drop(start_bx); // Codegen the body of each block using reverse postorder - for (bb, _) in traversal::reverse_postorder(&mir) { + for (bb, _) in traversal::reverse_postorder(mir) { fx.codegen_block(bb); } } diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 8e5019967a46..02b51dfe5bf7 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -702,7 +702,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { }; let fn_ptr = bx.get_fn_addr(instance); let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty()); - let fn_ty = bx.fn_decl_backend_type(&fn_abi); + let fn_ty = bx.fn_decl_backend_type(fn_abi); let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() { Some(bx.tcx().codegen_fn_attrs(instance.def_id())) } else { diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index 6fbf992eda9e..295e27691090 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -34,7 +34,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { } MonoItem::GlobalAsm(item_id) => { let item = cx.tcx().hir().item(item_id); - if let hir::ItemKind::GlobalAsm(ref asm) = item.kind { + if let hir::ItemKind::GlobalAsm(asm) = item.kind { let operands: Vec<_> = asm .operands .iter() @@ -88,7 +88,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { } } MonoItem::Fn(instance) => { - base::codegen_instance::(&cx, instance); + base::codegen_instance::(cx, instance); } } @@ -119,10 +119,10 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { match *self { MonoItem::Static(def_id) => { - cx.predefine_static(def_id, linkage, visibility, &symbol_name); + cx.predefine_static(def_id, linkage, visibility, symbol_name); } MonoItem::Fn(instance) => { - cx.predefine_fn(instance, linkage, visibility, &symbol_name); + cx.predefine_fn(instance, linkage, visibility, symbol_name); } MonoItem::GlobalAsm(..) => {} } diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 13937a94198d..edfece07d190 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -314,7 +314,7 @@ pub fn eval_in_interpreter<'mir, 'tcx>( is_static: bool, ) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> { let res = ecx.load_mir(cid.instance.def, cid.promoted); - match res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body)) { + match res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, body)) { Err(error) => { let (error, backtrace) = error.into_parts(); backtrace.print_backtrace(); diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 739dbcc5aba6..bc0327db22e7 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -200,7 +200,7 @@ impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> { &caller .file .name - .for_scope(&self.tcx.sess, RemapPathScopeComponents::DIAGNOSTICS) + .for_scope(self.tcx.sess, RemapPathScopeComponents::DIAGNOSTICS) .to_string_lossy(), ), u32::try_from(caller.line).unwrap(), diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 2bee4b45ad02..854fe9a0765f 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -387,7 +387,7 @@ fn valtree_into_mplace<'tcx>( debug!(?place_inner); valtree_into_mplace(ecx, &place_inner, *inner_valtree); - dump_place(&ecx, &place_inner); + dump_place(ecx, &place_inner); } debug!("dump of place_adjusted:"); diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index f4cb12c8d436..d296ff5928b3 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -256,7 +256,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let addr = addr.to_target_usize(self)?; // Then turn address into pointer. - let ptr = M::ptr_from_addr_cast(&self, addr)?; + let ptr = M::ptr_from_addr_cast(self, addr)?; Ok(ImmTy::from_scalar(Scalar::from_maybe_pointer(ptr, self), cast_to)) } diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index 3d90e95c09c7..413963b2fdcb 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -259,7 +259,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx, const_eval::Memory // to avoid could be expensive: on the potentially larger types, arrays and slices, // rather than on all aggregates unconditionally. if matches!(mplace.layout.ty.kind(), ty::Array(..) | ty::Slice(..)) { - let Some((size, _align)) = self.ecx.size_and_align_of_mplace(&mplace)? else { + let Some((size, _align)) = self.ecx.size_and_align_of_mplace(mplace)? else { // We do the walk if we can't determine the size of the mplace: we may be // dealing with extern types here in the future. return Ok(true); diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index b23cafc193a0..80e14f5a884d 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -505,7 +505,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Performs an exact division, resulting in undefined behavior where // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`. // First, check x % y != 0 (or if that computation overflows). - let (res, overflow) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?; + let (res, overflow) = self.overflowing_binary_op(BinOp::Rem, a, b)?; assert!(!overflow); // All overflow is UB, so this should never return on overflow. if res.to_scalar().assert_bits(a.layout.size) != 0 { throw_ub_custom!( @@ -515,7 +515,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ) } // `Rem` says this is all right, so we can let `Div` do its job. - self.binop_ignore_overflow(BinOp::Div, &a, &b, dest) + self.binop_ignore_overflow(BinOp::Div, a, b, dest) } pub fn saturating_arith( diff --git a/compiler/rustc_const_eval/src/interpret/operator.rs b/compiler/rustc_const_eval/src/interpret/operator.rs index 538077a0b777..eef154257646 100644 --- a/compiler/rustc_const_eval/src/interpret/operator.rs +++ b/compiler/rustc_const_eval/src/interpret/operator.rs @@ -20,7 +20,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { right: &ImmTy<'tcx, M::Provenance>, dest: &PlaceTy<'tcx, M::Provenance>, ) -> InterpResult<'tcx> { - let (val, overflowed) = self.overflowing_binary_op(op, &left, &right)?; + let (val, overflowed) = self.overflowing_binary_op(op, left, right)?; debug_assert_eq!( Ty::new_tup(self.tcx.tcx, &[val.layout.ty, self.tcx.types.bool]), dest.layout.ty, diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index 09ffdec7de7d..2ad0c9a87310 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -456,7 +456,7 @@ where ) -> InterpResult<'tcx, Option>> { let (size, _align) = self - .size_and_align_of_mplace(&mplace)? + .size_and_align_of_mplace(mplace)? .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); // We check alignment separately, and *after* checking everything else. // If an access is both OOB and misaligned, we want to see the bounds error. @@ -472,7 +472,7 @@ where ) -> InterpResult<'tcx, Option>> { let (size, _align) = self - .size_and_align_of_mplace(&mplace)? + .size_and_align_of_mplace(mplace)? .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); // We check alignment separately, and raise that error *after* checking everything else. // If an access is both OOB and misaligned, we want to see the bounds error. diff --git a/compiler/rustc_const_eval/src/interpret/terminator.rs b/compiler/rustc_const_eval/src/interpret/terminator.rs index b54c66814563..debae6c89024 100644 --- a/compiler/rustc_const_eval/src/interpret/terminator.rs +++ b/compiler/rustc_const_eval/src/interpret/terminator.rs @@ -51,7 +51,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { match arg { FnArg::Copy(op) => Ok(op.clone()), - FnArg::InPlace(place) => self.place_to_op(&place), + FnArg::InPlace(place) => self.place_to_op(place), } } @@ -410,7 +410,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // so we implement a type-based check that reflects the guaranteed rules for ABI compatibility. if self.layout_compat(caller_abi.layout, callee_abi.layout)? { // Ensure that our checks imply actual ABI compatibility for this concrete call. - assert!(caller_abi.eq_abi(&callee_abi)); + assert!(caller_abi.eq_abi(callee_abi)); return Ok(true); } else { trace!( @@ -464,7 +464,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // We work with a copy of the argument for now; if this is in-place argument passing, we // will later protect the source it comes from. This means the callee cannot observe if we // did in-place of by-copy argument passing, except for pointer equality tests. - let caller_arg_copy = self.copy_fn_arg(&caller_arg)?; + let caller_arg_copy = self.copy_fn_arg(caller_arg)?; if !already_live { let local = callee_arg.as_local().unwrap(); let meta = caller_arg_copy.meta(); diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index d21fef58f3f8..20f251d5c91a 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -896,7 +896,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self }; // Run it. - match visitor.visit_value(&op) { + match visitor.visit_value(op) { Ok(()) => Ok(()), // Pass through validation failures and "invalid program" issues. Err(err) diff --git a/compiler/rustc_const_eval/src/interpret/visitor.rs b/compiler/rustc_const_eval/src/interpret/visitor.rs index fc21ad1f1834..5c5a6e8db57a 100644 --- a/compiler/rustc_const_eval/src/interpret/visitor.rs +++ b/compiler/rustc_const_eval/src/interpret/visitor.rs @@ -97,14 +97,14 @@ pub trait ValueVisitor<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized { let inner_mplace = self.ecx().unpack_dyn_trait(&dest)?.0; trace!("walk_value: dyn object layout: {:#?}", inner_mplace.layout); // recurse with the inner type - return self.visit_field(&v, 0, &inner_mplace.into()); + return self.visit_field(v, 0, &inner_mplace.into()); } ty::Dynamic(_, _, ty::DynStar) => { // DynStar types. Very different from a dyn type (but strangely part of the // same variant in `TyKind`): These are pairs where the 2nd component is the // vtable, and the first component is the data (which must be ptr-sized). let data = self.ecx().unpack_dyn_star(v)?.0; - return self.visit_field(&v, 0, &data); + return self.visit_field(v, 0, &data); } // Slices do not need special handling here: they have `Array` field // placement with length 0, so we enter the `Array` case below which 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 76116e339859..13742ad273b5 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -60,9 +60,9 @@ impl<'mir, 'tcx> Qualifs<'mir, 'tcx> { let ConstCx { tcx, body, .. } = *ccx; FlowSensitiveAnalysis::new(NeedsDrop, ccx) - .into_engine(tcx, &body) + .into_engine(tcx, body) .iterate_to_fixpoint() - .into_results_cursor(&body) + .into_results_cursor(body) }); needs_drop.seek_before_primary_effect(location); @@ -122,9 +122,9 @@ impl<'mir, 'tcx> Qualifs<'mir, 'tcx> { let ConstCx { tcx, body, .. } = *ccx; FlowSensitiveAnalysis::new(HasMutInterior, ccx) - .into_engine(tcx, &body) + .into_engine(tcx, body) .iterate_to_fixpoint() - .into_results_cursor(&body) + .into_results_cursor(body) }); has_mut_interior.seek_before_primary_effect(location); @@ -170,9 +170,9 @@ impl<'mir, 'tcx> Qualifs<'mir, 'tcx> { hir::ConstContext::Const { .. } | hir::ConstContext::Static(_) => { let mut cursor = FlowSensitiveAnalysis::new(CustomEq, ccx) - .into_engine(ccx.tcx, &ccx.body) + .into_engine(ccx.tcx, ccx.body) .iterate_to_fixpoint() - .into_results_cursor(&ccx.body); + .into_results_cursor(ccx.body); cursor.seek_after_primary_effect(return_loc); cursor.get().contains(RETURN_PLACE) @@ -225,7 +225,7 @@ impl<'mir, 'tcx> Deref for Checker<'mir, 'tcx> { type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { - &self.ccx + self.ccx } } @@ -272,7 +272,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { } if !tcx.has_attr(def_id, sym::rustc_do_not_const_check) { - self.visit_body(&body); + self.visit_body(body); } // If we got through const-checking without emitting any "primary" errors, emit any @@ -503,7 +503,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Fake, place) | Rvalue::AddressOf(Mutability::Not, place) => { let borrowed_place_has_mut_interior = qualifs::in_place::( - &self.ccx, + self.ccx, &mut |local| self.qualifs.has_mut_interior(self.ccx, local, location), place.as_ref(), ); diff --git a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs index e51082e1ec0e..095e119d38c5 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs @@ -83,7 +83,7 @@ pub fn rustc_allow_const_fn_unstable( feature_gate: Symbol, ) -> bool { let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id)); - attr::rustc_allow_const_fn_unstable(&tcx.sess, attrs).any(|name| name == feature_gate) + attr::rustc_allow_const_fn_unstable(tcx.sess, attrs).any(|name| name == feature_gate) } /// Returns `true` if the given `const fn` is "const-stable". diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index 40183baccf8f..ca63eb135bda 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -129,7 +129,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { tcx, generics, err, - ¶m_ty.name.as_str(), + param_ty.name.as_str(), &constraint, None, None, diff --git a/compiler/rustc_const_eval/src/transform/check_consts/post_drop_elaboration.rs b/compiler/rustc_const_eval/src/transform/check_consts/post_drop_elaboration.rs index aff256b3eadd..06371438ec1a 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/post_drop_elaboration.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/post_drop_elaboration.rs @@ -54,7 +54,7 @@ impl<'mir, 'tcx> std::ops::Deref for CheckLiveDrops<'mir, 'tcx> { type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { - &self.ccx + self.ccx } } diff --git a/compiler/rustc_const_eval/src/transform/promote_consts.rs b/compiler/rustc_const_eval/src/transform/promote_consts.rs index b3d6b891b118..66b813e4e595 100644 --- a/compiler/rustc_const_eval/src/transform/promote_consts.rs +++ b/compiler/rustc_const_eval/src/transform/promote_consts.rs @@ -188,7 +188,7 @@ impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> { type Target = ConstCx<'a, 'tcx>; fn deref(&self) -> &Self::Target { - &self.ccx + self.ccx } } @@ -229,7 +229,7 @@ impl<'tcx> Validator<'_, 'tcx> { let statement = &self.body[loc.block].statements[loc.statement_index]; match &statement.kind { StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::( - &self.ccx, + self.ccx, &mut |l| self.qualif_local::(l), rhs, ), @@ -246,7 +246,7 @@ impl<'tcx> Validator<'_, 'tcx> { match &terminator.kind { TerminatorKind::Call { .. } => { let return_ty = self.body.local_decls[local].ty; - Q::in_any_value_of_ty(&self.ccx, return_ty) + Q::in_any_value_of_ty(self.ccx, return_ty) } kind => { span_bug!(terminator.source_info.span, "{:?} not promotable", kind); diff --git a/compiler/rustc_data_structures/src/sharded.rs b/compiler/rustc_data_structures/src/sharded.rs index 639f05c9e524..162dbd234d67 100644 --- a/compiler/rustc_data_structures/src/sharded.rs +++ b/compiler/rustc_data_structures/src/sharded.rs @@ -50,7 +50,7 @@ impl Sharded { #[inline] pub fn get_shard_by_value(&self, _val: &K) -> &Lock { match self { - Self::Single(single) => &single, + Self::Single(single) => single, #[cfg(parallel_compiler)] Self::Shards(..) => self.get_shard_by_hash(make_hash(_val)), } @@ -64,7 +64,7 @@ impl Sharded { #[inline] pub fn get_shard_by_index(&self, _i: usize) -> &Lock { match self { - Self::Single(single) => &single, + Self::Single(single) => single, #[cfg(parallel_compiler)] Self::Shards(shards) => { // SAFETY: The index gets ANDed with the shard mask, ensuring it is always inbounds. diff --git a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs index 203e529120b3..da266bf9c63e 100644 --- a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs +++ b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs @@ -138,7 +138,7 @@ impl AnnotateSnippetEmitterWriter { let message = self.translate_messages(messages, args); if let Some(source_map) = &self.source_map { // Make sure our primary file comes first - let primary_lo = if let Some(ref primary_span) = msp.primary_span().as_ref() { + let primary_lo = if let Some(primary_span) = msp.primary_span().as_ref() { if primary_span.is_dummy() { // FIXME(#59346): Not sure when this is the case and what // should be done if it happens @@ -203,7 +203,7 @@ impl AnnotateSnippetEmitterWriter { Slice { source, line_start: *line_index, - origin: Some(&file_name), + origin: Some(file_name), // FIXME(#59346): Not really sure when `fold` should be true or false fold: false, annotations: annotations diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 68dba8602912..ba9cd02a9ece 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -1297,7 +1297,7 @@ impl EmitterWriter { buffer.append(line_number, line, style_or_override(*style, override_style)); } } else { - buffer.append(line_number, &text, style_or_override(*style, override_style)); + buffer.append(line_number, text, style_or_override(*style, override_style)); } } } @@ -1931,7 +1931,7 @@ impl EmitterWriter { self.draw_code_line( &mut buffer, &mut row_num, - &highlight_parts, + highlight_parts, line_pos + line_start, line, show_code_change, @@ -2338,7 +2338,7 @@ impl FileWithAnnotatedLines { let mut output = vec![]; let mut multiline_annotations = vec![]; - if let Some(ref sm) = emitter.source_map() { + if let Some(sm) = emitter.source_map() { for SpanLabel { span, is_primary, label } in msp.span_labels() { // If we don't have a useful span, pick the primary span if that exists. // Worst case we'll just print an error at the top of the main file. @@ -2362,7 +2362,7 @@ impl FileWithAnnotatedLines { let label = label.as_ref().map(|m| { normalize_whitespace( - &emitter.translate_message(m, &args).map_err(Report::new).unwrap(), + &emitter.translate_message(m, args).map_err(Report::new).unwrap(), ) }); diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index c4d2a374f0c6..88e90a3b3d14 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -777,7 +777,7 @@ impl SyntaxExtension { attrs: &[ast::Attribute], ) -> SyntaxExtension { let allow_internal_unstable = - attr::allow_internal_unstable(sess, &attrs).collect::>(); + attr::allow_internal_unstable(sess, attrs).collect::>(); let allow_internal_unsafe = attr::contains_name(attrs, sym::allow_internal_unsafe); let local_inner_macros = attr::find_by_name(attrs, sym::macro_export) @@ -796,9 +796,9 @@ impl SyntaxExtension { ) }) .unwrap_or_else(|| (None, helper_attrs)); - let stability = attr::find_stability(&sess, attrs, span); - let const_stability = attr::find_const_stability(&sess, attrs, span); - let body_stability = attr::find_body_stability(&sess, attrs); + let stability = attr::find_stability(sess, attrs, span); + let const_stability = attr::find_const_stability(sess, attrs, span); + let body_stability = attr::find_body_stability(sess, attrs); if let Some((_, sp)) = const_stability { sess.emit_err(errors::MacroConstStability { span: sp, @@ -818,7 +818,7 @@ impl SyntaxExtension { allow_internal_unstable: (!allow_internal_unstable.is_empty()) .then(|| allow_internal_unstable.into()), stability: stability.map(|(s, _)| s), - deprecation: attr::find_deprecation(&sess, features, attrs).map(|(d, _)| d), + deprecation: attr::find_deprecation(sess, features, attrs).map(|(d, _)| d), helper_attrs, edition, builtin_name, @@ -1464,7 +1464,7 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool { if crate_matches { sess.buffer_lint_with_diagnostic( - &PROC_MACRO_BACK_COMPAT, + PROC_MACRO_BACK_COMPAT, item.ident.span, ast::CRATE_NODE_ID, "using an old version of `rental`", diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 0d76b1b29746..5ccef343b172 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -434,9 +434,9 @@ impl<'a> StripUnconfigured<'a> { } }; ( - parse_cfg(&meta_item, &self.sess).map_or(true, |meta_item| { + parse_cfg(&meta_item, self.sess).map_or(true, |meta_item| { attr::cfg_matches( - &meta_item, + meta_item, &self.sess.parse_sess, self.lint_node_id, self.features, diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index f87f4aba2b9e..1b51d80fb386 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1096,7 +1096,7 @@ impl InvocationCollectorNode for P { ModKind::Loaded(_, inline, _) => { // Inline `mod foo { ... }`, but we still need to push directories. let (dir_path, dir_ownership) = mod_dir_path( - &ecx.sess, + ecx.sess, ident, &attrs, &ecx.current_expansion.module, @@ -1111,7 +1111,7 @@ impl InvocationCollectorNode for P { let old_attrs_len = attrs.len(); let ParsedExternalMod { items, spans, file_path, dir_path, dir_ownership } = parse_external_mod( - &ecx.sess, + ecx.sess, ident, span, &ecx.current_expansion.module, @@ -1168,14 +1168,14 @@ impl InvocationCollectorNode for P { ast::UseTreeKind::Simple(_) => idents.push(ut.ident()), ast::UseTreeKind::Nested(nested) => { for (ut, _) in nested { - collect_use_tree_leaves(&ut, idents); + collect_use_tree_leaves(ut, idents); } } } } let mut idents = Vec::new(); - collect_use_tree_leaves(&ut, &mut idents); + collect_use_tree_leaves(ut, &mut idents); return idents; } @@ -1531,7 +1531,7 @@ impl InvocationCollectorNode for AstNodeWrapper, OptExprTag> { } } fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) { - cfg.maybe_emit_expr_attr_err(&attr); + cfg.maybe_emit_expr_attr_err(attr); } } @@ -1580,7 +1580,7 @@ struct InvocationCollector<'a, 'b> { impl<'a, 'b> InvocationCollector<'a, 'b> { fn cfg(&self) -> StripUnconfigured<'_> { StripUnconfigured { - sess: &self.cx.sess, + sess: self.cx.sess, features: Some(self.cx.ecfg.features), config_tokens: false, lint_node_id: self.cx.current_expansion.lint_node_id, @@ -1693,7 +1693,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { if attr.is_doc_comment() { self.cx.sess.parse_sess.buffer_lint_with_diagnostic( - &UNUSED_DOC_COMMENTS, + UNUSED_DOC_COMMENTS, current_span, self.cx.current_expansion.lint_node_id, "unused doc comment", @@ -1705,7 +1705,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // eagerly evaluated. if attr_name != sym::cfg && attr_name != sym::cfg_attr { self.cx.sess.parse_sess.buffer_lint_with_diagnostic( - &UNUSED_ATTRIBUTES, + UNUSED_ATTRIBUTES, attr.span, self.cx.current_expansion.lint_node_id, format!("unused attribute `{attr_name}`"), diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 95f5bb2d2e23..42c91824baf5 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -650,6 +650,6 @@ fn buffer_lint( ) { // Macros loaded from other crates have dummy node ids. if node_id != DUMMY_NODE_ID { - sess.buffer_lint(&META_VARIABLE_MISUSE, span, node_id, message); + sess.buffer_lint(META_VARIABLE_MISUSE, span, node_id, message); } } diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index 1c78232a0f34..965beb9bf84e 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -483,7 +483,7 @@ impl TtParser { if matches!(t, Token { kind: DocComment(..), .. }) { mp.idx += 1; self.cur_mps.push(mp); - } else if token_name_eq(&t, token) { + } else if token_name_eq(t, token) { mp.idx += 1; self.next_mps.push(mp); } diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index ebdd3cb547c3..bc3f0ce5a70b 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -213,7 +213,7 @@ fn expand_macro<'cx>( let arm_span = rhses[i].span(); // rhs has holes ( `$id` and `$(...)` that need filled) - let mut tts = match transcribe(cx, &named_matches, &rhs, rhs_span, transparency) { + let mut tts = match transcribe(cx, &named_matches, rhs, rhs_span, transparency) { Ok(tts) => tts, Err(mut err) => { err.emit(); @@ -511,7 +511,7 @@ pub fn compile_declarative_macro( ) .pop() .unwrap(); - valid &= check_lhs_nt_follows(&sess.parse_sess, &def, &tt); + valid &= check_lhs_nt_follows(&sess.parse_sess, def, &tt); return tt; } sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") @@ -927,7 +927,7 @@ impl<'tt> TtHandle<'tt> { fn get(&'tt self) -> &'tt mbe::TokenTree { match self { TtHandle::TtRef(tt) => tt, - TtHandle::Token(token_tt) => &token_tt, + TtHandle::Token(token_tt) => token_tt, } } } @@ -1170,7 +1170,7 @@ fn check_matcher_core<'tt>( Some(NonterminalKind::PatParam { inferred: false }), )); sess.buffer_lint_with_diagnostic( - &RUST_2021_INCOMPATIBLE_OR_PATTERNS, + RUST_2021_INCOMPATIBLE_OR_PATTERNS, span, ast::CRATE_NODE_ID, "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro", @@ -1407,7 +1407,7 @@ fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow { fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String { match tt { - mbe::TokenTree::Token(token) => pprust::token_to_string(&token).into(), + mbe::TokenTree::Token(token) => pprust::token_to_string(token).into(), mbe::TokenTree::MetaVar(_, name) => format!("${name}"), mbe::TokenTree::MetaVarDecl(_, name, Some(kind)) => format!("${name}:{kind}"), mbe::TokenTree::MetaVarDecl(_, name, None) => format!("${name}:"), diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index 6546199f5e6a..6c6dfe533058 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -116,7 +116,7 @@ pub(super) fn parse( fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &ParseSess, span: Span) { if !features.macro_metavar_expr { let msg = "meta-variable expressions are unstable"; - feature_err(&sess, sym::macro_metavar_expr, span, msg).emit(); + feature_err(sess, sym::macro_metavar_expr, span, msg).emit(); } } @@ -174,7 +174,7 @@ fn parse_tree<'a>( // The delimiter is `{`. This indicates the beginning // of a meta-variable expression (e.g. `${count(ident)}`). // Try to parse the meta-variable expression. - match MetaVarExpr::parse(&tts, delim_span.entire(), sess) { + match MetaVarExpr::parse(tts, delim_span.entire(), sess) { Err(mut err) => { err.emit(); // Returns early the same read `$` to avoid spanning @@ -242,10 +242,8 @@ fn parse_tree<'a>( // `tree` is followed by some other token. This is an error. Some(tokenstream::TokenTree::Token(token, _)) => { - let msg = format!( - "expected identifier, found `{}`", - pprust::token_to_string(&token), - ); + let msg = + format!("expected identifier, found `{}`", pprust::token_to_string(token),); sess.span_diagnostic.span_err(token.span, msg); TokenTree::MetaVar(token.span, Ident::empty()) } @@ -291,7 +289,7 @@ fn parse_kleene_op<'a>( span: Span, ) -> Result, Span> { match input.next() { - Some(tokenstream::TokenTree::Token(token, _)) => match kleene_op(&token) { + Some(tokenstream::TokenTree::Token(token, _)) => match kleene_op(token) { Some(op) => Ok(Ok((op, token.span))), None => Ok(Err(token.clone())), }, diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 15e7ab3fe3ee..bc03fc0d1b16 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -90,7 +90,7 @@ pub(super) fn transcribe<'a>( // We descend into the RHS (`src`), expanding things as we go. This stack contains the things // we have yet to expand/are still expanding. We start the stack off with the whole RHS. - let mut stack: SmallVec<[Frame<'_>; 1]> = smallvec![Frame::new(&src, src_span)]; + let mut stack: SmallVec<[Frame<'_>; 1]> = smallvec![Frame::new(src, src_span)]; // As we descend in the RHS, we will need to be able to match nested sequences of matchers. // `repeats` keeps track of where we are in matching at each level, with the last element being @@ -166,7 +166,7 @@ pub(super) fn transcribe<'a>( // and the matches in `interp` have the same shape. Otherwise, either the caller or the // macro writer has made a mistake. seq @ mbe::TokenTree::Sequence(_, delimited) => { - match lockstep_iter_size(&seq, interp, &repeats) { + match lockstep_iter_size(seq, interp, &repeats) { LockstepIterSize::Unconstrained => { return Err(cx.create_err(NoSyntaxVarsExprRepeat { span: seq.span() })); } @@ -250,7 +250,7 @@ pub(super) fn transcribe<'a>( // Replace meta-variable expressions with the result of their expansion. mbe::TokenTree::MetaVarExpr(sp, expr) => { - transcribe_metavar_expr(cx, expr, interp, &mut marker, &repeats, &mut result, &sp)?; + transcribe_metavar_expr(cx, expr, interp, &mut marker, &repeats, &mut result, sp)?; } // If we are entering a new delimiter, we push its contents to the `stack` to be @@ -529,7 +529,7 @@ fn transcribe_metavar_expr<'a>( match *expr { MetaVarExpr::Count(original_ident, depth_opt) => { let matched = matched_from_ident(cx, original_ident, interp)?; - let count = count_repetitions(cx, depth_opt, matched, &repeats, sp)?; + let count = count_repetitions(cx, depth_opt, matched, repeats, sp)?; let tt = TokenTree::token_alone( TokenKind::lit(token::Integer, sym::integer(count), None), visited_span(), diff --git a/compiler/rustc_expand/src/module.rs b/compiler/rustc_expand/src/module.rs index df6bdc6952bd..a0dec89d6311 100644 --- a/compiler/rustc_expand/src/module.rs +++ b/compiler/rustc_expand/src/module.rs @@ -57,7 +57,7 @@ pub(crate) fn parse_external_mod( // We bail on the first error, but that error does not cause a fatal error... (1) let result: Result<_, ModError<'_>> = try { // Extract the file path and the new ownership. - let mp = mod_file_path(sess, ident, &attrs, &module.dir_path, dir_ownership)?; + let mp = mod_file_path(sess, ident, attrs, &module.dir_path, dir_ownership)?; dir_ownership = mp.dir_ownership; // Ensure file paths are acyclic. @@ -119,7 +119,7 @@ pub(crate) fn mod_dir_path( Inline::No => { // FIXME: This is a subset of `parse_external_mod` without actual parsing, // check whether the logic for unloaded, loaded and inline modules can be unified. - let file_path = mod_file_path(sess, ident, &attrs, &module.dir_path, dir_ownership) + let file_path = mod_file_path(sess, ident, attrs, &module.dir_path, dir_ownership) .map(|mp| { dir_ownership = mp.dir_ownership; mp.file_path diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 41ec0ed84f70..b057a645f819 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -784,6 +784,6 @@ impl server::Server for Rustc<'_, '_> { } fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { - f(&symbol.as_str()) + f(symbol.as_str()) } } diff --git a/compiler/rustc_hir_analysis/src/astconv/errors.rs b/compiler/rustc_hir_analysis/src/astconv/errors.rs index 8f4b83966dff..5a70a842f0d9 100644 --- a/compiler/rustc_hir_analysis/src/astconv/errors.rs +++ b/compiler/rustc_hir_analysis/src/astconv/errors.rs @@ -227,7 +227,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.tcx(), generics, &mut err, - &ty_param_name, + ty_param_name, &trait_name, None, None, diff --git a/compiler/rustc_hir_analysis/src/astconv/lint.rs b/compiler/rustc_hir_analysis/src/astconv/lint.rs index bc57bbcca62e..14e810d13365 100644 --- a/compiler/rustc_hir_analysis/src/astconv/lint.rs +++ b/compiler/rustc_hir_analysis/src/astconv/lint.rs @@ -106,7 +106,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); } // check if the impl trait that we are considering is a impl of a local trait - self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag); + self.maybe_lint_blanket_trait_impl(self_ty, &mut diag); diag.stash(self_ty.span, StashKey::TraitMissingMethod); } else { let msg = "trait objects without an explicit `dyn` are deprecated"; @@ -121,7 +121,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { sugg, Applicability::MachineApplicable, ); - self.maybe_lint_blanket_trait_impl(&self_ty, lint); + self.maybe_lint_blanket_trait_impl(self_ty, lint); lint }, ); diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 3542fc7cd332..102c83751aad 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -1666,7 +1666,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .copied() .filter(|&(impl_, _)| { infcx.probe(|_| { - let ocx = ObligationCtxt::new(&infcx); + let ocx = ObligationCtxt::new(infcx); ocx.register_obligations(obligations.clone()); let impl_args = infcx.fresh_args_for_item(span, impl_); @@ -1979,7 +1979,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { types_and_spans[..types_and_spans.len() - 1] .iter() .map(|(x, _)| x.as_str()) - .intersperse(&", ") + .intersperse(", ") .collect::() ), [(only, _)] => only.to_string(), diff --git a/compiler/rustc_hir_analysis/src/autoderef.rs b/compiler/rustc_hir_analysis/src/autoderef.rs index 39db295044ed..5fc500f48076 100644 --- a/compiler/rustc_hir_analysis/src/autoderef.rs +++ b/compiler/rustc_hir_analysis/src/autoderef.rs @@ -182,7 +182,7 @@ impl<'a, 'tcx> Autoderef<'a, 'tcx> { } }; - let errors = fulfill_cx.select_where_possible(&self.infcx); + let errors = fulfill_cx.select_where_possible(self.infcx); if !errors.is_empty() { // This shouldn't happen, except for evaluate/fulfill mismatches, // but that's not a reason for an ICE (`predicate_may_hold` is conservative diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index e61ca232de64..e301f0b22ef7 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -222,11 +222,11 @@ fn check_opaque(tcx: TyCtxt<'_>, id: hir::ItemId) { if tcx.type_of(item.owner_id.def_id).instantiate_identity().references_error() { return; } - if check_opaque_for_cycles(tcx, item.owner_id.def_id, args, span, &origin).is_err() { + if check_opaque_for_cycles(tcx, item.owner_id.def_id, args, span, origin).is_err() { return; } - let _ = check_opaque_meets_bounds(tcx, item.owner_id.def_id, span, &origin); + let _ = check_opaque_meets_bounds(tcx, item.owner_id.def_id, span, origin); } /// Checks that an opaque type does not contain cycles. @@ -518,7 +518,7 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) { DefKind::TyAlias => { let pty_ty = tcx.type_of(id.owner_id).instantiate_identity(); let generics = tcx.generics_of(id.owner_id); - check_type_params_are_used(tcx, &generics, pty_ty); + check_type_params_are_used(tcx, generics, pty_ty); } DefKind::ForeignMod => { let it = tcx.hir().item(id); @@ -900,7 +900,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) { let repr = def.repr(); if repr.packed() { for attr in tcx.get_attrs(def.did(), sym::repr) { - for r in attr::parse_repr_attr(&tcx.sess, attr) { + for r in attr::parse_repr_attr(tcx.sess, attr) { if let attr::ReprPacked(pack) = r && let Some(repr_pack) = repr.pack && pack as u64 != repr_pack.bytes() @@ -1150,8 +1150,8 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) { let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_)); let has_non_units = def.variants().iter().any(|var| !is_unit(var)); - let disr_units = def.variants().iter().any(|var| is_unit(&var) && has_disr(&var)); - let disr_non_unit = def.variants().iter().any(|var| !is_unit(&var) && has_disr(&var)); + let disr_units = def.variants().iter().any(|var| is_unit(var) && has_disr(var)); + let disr_non_unit = def.variants().iter().any(|var| !is_unit(var) && has_disr(var)); if disr_non_unit || (disr_units && has_non_units) { let mut err = struct_span_err!( diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index f026f78cc2b4..d93bb48e0fe3 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -307,7 +307,7 @@ fn compare_method_predicate_entailment<'tcx>( debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed"); let emitted = report_trait_method_mismatch( - &infcx, + infcx, cause, terr, (trait_m, trait_sig), @@ -1140,7 +1140,7 @@ fn report_trait_method_mismatch<'tcx>( ) -> ErrorGuaranteed { let tcx = infcx.tcx; let (impl_err_span, trait_err_span) = - extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m); + extract_spans_for_error_reporting(infcx, terr, &cause, impl_m, trait_m); let mut diag = struct_span_err!( tcx.sess, diff --git a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index cd7e99172045..ba627c740dfc 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -307,7 +307,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { if let Err(msg) = reg.validate( asm_arch, self.tcx.sess.relocation_model(), - &target_features, + target_features, &self.tcx.sess.target, op.is_clobber(), ) { @@ -382,7 +382,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { asm.template, true, None, - &target_features, + target_features, ); } hir::InlineAsmOperand::Out { reg, late: _, expr } => { @@ -394,7 +394,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { asm.template, false, None, - &target_features, + target_features, ); } } @@ -406,7 +406,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { asm.template, false, None, - &target_features, + target_features, ); } hir::InlineAsmOperand::SplitInOut { reg, late: _, in_expr, out_expr } => { @@ -417,7 +417,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { asm.template, true, None, - &target_features, + target_features, ); if let Some(out_expr) = out_expr { self.check_asm_operand_type( @@ -427,7 +427,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { asm.template, false, Some((in_expr, in_ty)), - &target_features, + target_features, ); } } diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 40b33117f7cc..9557568b3870 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -414,11 +414,11 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h // then we'll assign too low a count to any `yield` expressions // we encounter in 'right_expression' - they should really occur after all of the // expressions in 'left_expression'. - visitor.visit_expr(&right_expr); + visitor.visit_expr(right_expr); visitor.pessimistic_yield = prev_pessimistic; debug!("resolve_expr - restoring pessimistic_yield to {}", prev_pessimistic); - visitor.visit_expr(&left_expr); + visitor.visit_expr(left_expr); debug!("resolve_expr - fixing up counts to {}", visitor.expr_and_pat_count); // Remove and process any scopes pushed by the visitor @@ -582,7 +582,7 @@ fn resolve_local<'tcx>( // due to rule C. if let Some(expr) = init { - record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope); + record_rvalue_scope_if_borrow_expr(visitor, expr, blk_scope); if let Some(pat) = pat { if is_binding_pat(pat) { @@ -645,21 +645,19 @@ fn resolve_local<'tcx>( match pat.kind { PatKind::Binding(hir::BindingAnnotation(hir::ByRef::Yes, _), ..) => true, - PatKind::Struct(_, field_pats, _) => { - field_pats.iter().any(|fp| is_binding_pat(&fp.pat)) - } + PatKind::Struct(_, field_pats, _) => field_pats.iter().any(|fp| is_binding_pat(fp.pat)), PatKind::Slice(pats1, pats2, pats3) => { - pats1.iter().any(|p| is_binding_pat(&p)) - || pats2.iter().any(|p| is_binding_pat(&p)) - || pats3.iter().any(|p| is_binding_pat(&p)) + pats1.iter().any(|p| is_binding_pat(p)) + || pats2.iter().any(|p| is_binding_pat(p)) + || pats3.iter().any(|p| is_binding_pat(p)) } PatKind::Or(subpats) | PatKind::TupleStruct(_, subpats, _) - | PatKind::Tuple(subpats, _) => subpats.iter().any(|p| is_binding_pat(&p)), + | PatKind::Tuple(subpats, _) => subpats.iter().any(|p| is_binding_pat(p)), - PatKind::Box(subpat) => is_binding_pat(&subpat), + PatKind::Box(subpat) => is_binding_pat(subpat), PatKind::Ref(_, _) | PatKind::Binding(hir::BindingAnnotation(hir::ByRef::No, _), ..) @@ -700,20 +698,20 @@ fn resolve_local<'tcx>( } hir::ExprKind::Struct(_, fields, _) => { for field in fields { - record_rvalue_scope_if_borrow_expr(visitor, &field.expr, blk_id); + record_rvalue_scope_if_borrow_expr(visitor, field.expr, blk_id); } } hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => { for subexpr in subexprs { - record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); + record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id); } } hir::ExprKind::Cast(subexpr, _) => { - record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id) + record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id) } hir::ExprKind::Block(block, _) => { if let Some(subexpr) = block.expr { - record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); + record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id); } } hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) => { @@ -795,13 +793,13 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { // The arguments and `self` are parented to the fn. self.cx.var_parent = self.cx.parent.take(); for param in body.params { - self.visit_pat(¶m.pat); + self.visit_pat(param.pat); } // The body of the every fn is a root scope. self.cx.parent = self.cx.var_parent; if self.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() { - self.visit_expr(&body.value) + self.visit_expr(body.value) } else { // Only functions have an outer terminating (drop) scope, while // temporaries in constant initializers may be 'static, but only @@ -822,7 +820,7 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { // (i.e., `'static`), which means that after `g` returns, it drops, // and all the associated destruction scope rules apply. self.cx.var_parent = None; - resolve_local(self, None, Some(&body.value)); + resolve_local(self, None, Some(body.value)); } if body.coroutine_kind.is_some() { @@ -849,7 +847,7 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { resolve_expr(self, ex); } fn visit_local(&mut self, l: &'tcx Local<'tcx>) { - resolve_local(self, Some(&l.pat), l.init) + resolve_local(self, Some(l.pat), l.init) } } diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index d7b50d127cd8..177e4611cc92 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -584,7 +584,7 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable>>( // reflected in a where clause on the GAT itself. for (ty, ty_idx) in &types { // In our example, requires that `Self: 'a` - if ty_known_to_outlive(tcx, item_def_id, param_env, &wf_tys, *ty, *region_a) { + if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) { debug!(?ty_idx, ?region_a_idx); debug!("required clause: {ty} must outlive {region_a}"); // Translate into the generic parameters of the GAT. In @@ -623,7 +623,7 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable>>( if matches!(**region_b, ty::ReStatic | ty::ReError(_)) || region_a == region_b { continue; } - if region_known_to_outlive(tcx, item_def_id, param_env, &wf_tys, *region_a, *region_b) { + if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) { debug!(?region_a_idx, ?region_b_idx); debug!("required clause: {region_a} must outlive {region_b}"); // Translate into the generic parameters of the GAT. @@ -671,7 +671,7 @@ fn ty_known_to_outlive<'tcx>( ty: Ty<'tcx>, region: ty::Region<'tcx>, ) -> bool { - resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| { + resolve_regions_with_wf_tys(tcx, id, param_env, wf_tys, |infcx, region_bound_pairs| { let origin = infer::RelateParamBound(DUMMY_SP, ty, None); let outlives = &mut TypeOutlives::new(infcx, tcx, region_bound_pairs, None, param_env); outlives.type_must_outlive(origin, ty, region, ConstraintCategory::BoringNoLocation); @@ -688,7 +688,7 @@ fn region_known_to_outlive<'tcx>( region_a: ty::Region<'tcx>, region_b: ty::Region<'tcx>, ) -> bool { - resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |mut infcx, _| { + resolve_regions_with_wf_tys(tcx, id, param_env, wf_tys, |mut infcx, _| { use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate; let origin = infer::RelateRegionParamBound(DUMMY_SP); // `region_a: region_b` -> `region_b <= region_a` diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index 8d87cb57b907..7c1086bf4b4c 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -58,7 +58,7 @@ fn do_orphan_check_impl<'tcx>( tr.path.span, trait_ref, impl_.self_ty.span, - &impl_.generics, + impl_.generics, err, )? } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 7b5b049d254e..60bd7e1bdc10 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1090,7 +1090,7 @@ fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool { pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> { if let hir::FnRetTy::Return(ty) = output { if is_suggestable_infer_ty(ty) { - return Some(&*ty); + return Some(*ty); } } None @@ -1373,7 +1373,7 @@ fn impl_trait_ref( if let Some(ErrorGuaranteed { .. }) = check_impl_constness( tcx, tcx.is_const_trait_impl_raw(def_id.to_def_id()), - &ast_trait_ref, + ast_trait_ref, ) { // we have a const impl, but for a trait without `#[const_trait]`, so // without the host param. If we continue with the HIR trait ref, we get @@ -1394,7 +1394,7 @@ fn impl_trait_ref( let trait_ref = hir::TraitRef { path: &path, hir_ref_id: ast_trait_ref.hir_ref_id }; icx.astconv().instantiate_mono_trait_ref(&trait_ref, selfty) } else { - icx.astconv().instantiate_mono_trait_ref(&ast_trait_ref, selfty) + icx.astconv().instantiate_mono_trait_ref(ast_trait_ref, selfty) } }) .map(ty::EarlyBinder::bind) diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 3d60c57b9d5a..97f60c986751 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -182,7 +182,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { } let no_generics = hir::Generics::empty(); - let ast_generics = node.generics().unwrap_or(&no_generics); + let ast_generics = node.generics().unwrap_or(no_generics); let (opt_self, allow_defaults) = match node { Node::Item(item) => { match item.kind { @@ -458,11 +458,11 @@ fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option match &item.kind { - hir::TraitItemKind::Fn(sig, _) => has_late_bound_regions(tcx, &item.generics, sig.decl), + hir::TraitItemKind::Fn(sig, _) => has_late_bound_regions(tcx, item.generics, sig.decl), _ => None, }, Node::ImplItem(item) => match &item.kind { - hir::ImplItemKind::Fn(sig, _) => has_late_bound_regions(tcx, &item.generics, sig.decl), + hir::ImplItemKind::Fn(sig, _) => has_late_bound_regions(tcx, item.generics, sig.decl), _ => None, }, Node::ForeignItem(item) => match item.kind { diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 68d040d58460..92c383f37036 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -290,7 +290,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen } hir::WherePredicate::RegionPredicate(region_pred) => { - let r1 = icx.astconv().ast_region_to_region(®ion_pred.lifetime, None); + let r1 = icx.astconv().ast_region_to_region(region_pred.lifetime, None); predicates.extend(region_pred.bounds.iter().map(|bound| { let (r2, span) = match bound { hir::GenericBound::Outlives(lt) => { @@ -714,9 +714,9 @@ pub(super) fn type_param_predicates( let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id); let ast_generics = match tcx.hir().get(item_hir_id) { - Node::TraitItem(item) => &item.generics, + Node::TraitItem(item) => item.generics, - Node::ImplItem(item) => &item.generics, + Node::ImplItem(item) => item.generics, Node::Item(item) => { match item.kind { diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 53efc2c6e828..bfabf967ebcc 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -565,7 +565,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { let mut bound_vars = FxIndexMap::default(); debug!(?generics.params); for param in generics.params { - let (def_id, reg) = ResolvedArg::early(¶m); + let (def_id, reg) = ResolvedArg::early(param); bound_vars.insert(def_id, reg); } @@ -684,7 +684,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(), s: self.scope, }; - self.with(scope, |this| this.visit_ty(&mt.ty)); + self.with(scope, |this| this.visit_ty(mt.ty)); } hir::TyKind::OpaqueDef(item_id, lifetimes, _in_trait) => { // Resolve the lifetimes in the bounds to the lifetime defs in the generics. @@ -775,7 +775,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { } Type(bounds, ty) => { self.visit_early(trait_item.hir_id(), trait_item.generics, |this| { - this.visit_generics(&trait_item.generics); + this.visit_generics(trait_item.generics); for bound in bounds { this.visit_param_bound(bound); } @@ -847,7 +847,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { hir::FnRetTy::DefaultReturn(_) => None, hir::FnRetTy::Return(ty) => Some(ty), }; - self.visit_fn_like_elision(&fd.inputs, output, matches!(fk, intravisit::FnKind::Closure)); + self.visit_fn_like_elision(fd.inputs, output, matches!(fk, intravisit::FnKind::Closure)); intravisit::walk_fn_kind(self, fk); self.visit_nested_body(body_id) } @@ -894,7 +894,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { }; self.with(scope, |this| { walk_list!(this, visit_generic_param, bound_generic_params); - this.visit_ty(&bounded_ty); + this.visit_ty(bounded_ty); walk_list!(this, visit_param_bound, bounds); }) } @@ -1061,7 +1061,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { { let BoundVarContext { tcx, map, .. } = self; let mut this = BoundVarContext { tcx: *tcx, map, scope: &wrap_scope }; - let span = debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope)); + let span = debug_span!("scope", scope = ?TruncatedScopeDebug(this.scope)); { let _enter = span.enter(); f(&mut this); diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 5f82d9f06c6e..0148c71dbb5c 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -59,7 +59,7 @@ impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> { Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)), Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)), Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)), - Nested::Body(id) => state.print_expr(&self.body(id).value), + Nested::Body(id) => state.print_expr(self.body(id).value), Nested::BodyParamPat(id, i) => state.print_pat(self.body(id).params[i].pat), } } @@ -88,14 +88,14 @@ impl<'a> State<'a> { Node::AnonConst(a) => self.print_anon_const(a), Node::ConstBlock(a) => self.print_inline_const(a), Node::Expr(a) => self.print_expr(a), - Node::ExprField(a) => self.print_expr_field(&a), + Node::ExprField(a) => self.print_expr_field(a), Node::Stmt(a) => self.print_stmt(a), Node::PathSegment(a) => self.print_path_segment(a), Node::Ty(a) => self.print_type(a), Node::TypeBinding(a) => self.print_type_binding(a), Node::TraitRef(a) => self.print_trait_ref(a), Node::Pat(a) => self.print_pat(a), - Node::PatField(a) => self.print_patfield(&a), + Node::PatField(a) => self.print_patfield(a), Node::Arm(a) => self.print_arm(a), Node::Infer(_) => self.word("_"), Node::Block(a) => { @@ -260,7 +260,7 @@ impl<'a> State<'a> { self.word("*"); self.print_mt(mt, true); } - hir::TyKind::Ref(ref lifetime, ref mt) => { + hir::TyKind::Ref(lifetime, ref mt) => { self.word("&"); self.print_opt_lifetime(lifetime); self.print_mt(mt, false); @@ -281,7 +281,7 @@ impl<'a> State<'a> { } hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"), hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false), - hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => { + hir::TyKind::TraitObject(bounds, lifetime, syntax) => { if syntax == ast::TraitObjectSyntax::Dyn { self.word_space("dyn"); } @@ -517,10 +517,10 @@ impl<'a> State<'a> { self.end(); // need to close a box self.ann.nested(self, Nested::Body(body)); } - hir::ItemKind::Macro(ref macro_def, _) => { + hir::ItemKind::Macro(macro_def, _) => { self.print_mac_def(macro_def, &item.ident, item.span, |_| {}); } - hir::ItemKind::Mod(ref _mod) => { + hir::ItemKind::Mod(_mod) => { self.head("mod"); self.print_ident(item.ident); self.nbsp(); @@ -549,7 +549,7 @@ impl<'a> State<'a> { state.print_type(ty); }); } - hir::ItemKind::OpaqueTy(ref opaque_ty) => { + hir::ItemKind::OpaqueTy(opaque_ty) => { self.print_item_type(item, opaque_ty.generics, |state| { let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len()); for b in opaque_ty.bounds { @@ -1096,12 +1096,12 @@ impl<'a> State<'a> { self.space(); } self.cbox(INDENT_UNIT); - self.print_outer_attributes(&self.attrs(field.hir_id)); + self.print_outer_attributes(self.attrs(field.hir_id)); if !field.is_shorthand { self.print_ident(field.ident); self.word_space(":"); } - self.print_expr(&field.expr); + self.print_expr(field.expr); self.end() } @@ -1131,7 +1131,7 @@ impl<'a> State<'a> { args: &[hir::Expr<'_>], ) { let base_args = args; - self.print_expr_maybe_paren(&receiver, parser::PREC_POSTFIX); + self.print_expr_maybe_paren(receiver, parser::PREC_POSTFIX); self.word("."); self.print_ident(segment.ident); @@ -1217,7 +1217,7 @@ impl<'a> State<'a> { self.commasep(Consistent, &args, |s, arg| match *arg { AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked), AsmArg::Operand(op) => match *op { - hir::InlineAsmOperand::In { reg, ref expr } => { + hir::InlineAsmOperand::In { reg, expr } => { s.word("in"); s.popen(); s.word(format!("{reg}")); @@ -1236,7 +1236,7 @@ impl<'a> State<'a> { None => s.word("_"), } } - hir::InlineAsmOperand::InOut { reg, late, ref expr } => { + hir::InlineAsmOperand::InOut { reg, late, expr } => { s.word(if late { "inlateout" } else { "inout" }); s.popen(); s.word(format!("{reg}")); @@ -1244,7 +1244,7 @@ impl<'a> State<'a> { s.space(); s.print_expr(expr); } - hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => { + hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, ref out_expr } => { s.word(if late { "inlateout" } else { "inout" }); s.popen(); s.word(format!("{reg}")); @@ -1350,7 +1350,7 @@ impl<'a> State<'a> { hir::ExprKind::AddrOf(k, m, expr) => { self.print_expr_addr_of(k, m, expr); } - hir::ExprKind::Lit(ref lit) => { + hir::ExprKind::Lit(lit) => { self.print_literal(lit); } hir::ExprKind::Cast(expr, ty) => { @@ -1516,7 +1516,7 @@ impl<'a> State<'a> { self.word("asm!"); self.print_inline_asm(asm); } - hir::ExprKind::OffsetOf(container, ref fields) => { + hir::ExprKind::OffsetOf(container, fields) => { self.word("offset_of!("); self.print_type(container); self.word(","); @@ -1764,7 +1764,7 @@ impl<'a> State<'a> { if !empty { self.space(); } - self.commasep_cmnt(Consistent, &fields, |s, f| s.print_patfield(f), |f| f.pat.span); + self.commasep_cmnt(Consistent, fields, |s, f| s.print_patfield(f), |f| f.pat.span); if etc { if !fields.is_empty() { self.word_space(","); @@ -1864,7 +1864,7 @@ impl<'a> State<'a> { self.space(); } self.cbox(INDENT_UNIT); - self.print_outer_attributes(&self.attrs(field.hir_id)); + self.print_outer_attributes(self.attrs(field.hir_id)); if !field.is_shorthand { self.print_ident(field.ident); self.word_nbsp(":"); @@ -2164,7 +2164,7 @@ impl<'a> State<'a> { self.print_bounds(":", bounds); } hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { - ref lifetime, + lifetime, bounds, .. }) => { diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index 84e986488a6a..a29d9c95e5ea 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -42,7 +42,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // #55810: Type check patterns first so we get types for all bindings. let scrut_span = scrut.span.find_ancestor_inside(expr.span).unwrap_or(scrut.span); for arm in arms { - self.check_pat_top(&arm.pat, scrutinee_ty, Some(scrut_span), Some(scrut), None); + self.check_pat_top(arm.pat, scrutinee_ty, Some(scrut_span), Some(scrut), None); } // Now typecheck the blocks. @@ -92,7 +92,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.diverges.set(Diverges::Maybe); - let arm_ty = self.check_expr_with_expectation(&arm.body, expected); + let arm_ty = self.check_expr_with_expectation(arm.body, expected); all_arms_diverge &= self.diverges.get(); let opt_suggest_box_span = prior_arm.and_then(|(_, prior_arm_ty, _)| { @@ -137,7 +137,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { coercion.coerce_inner( self, &cause, - Some(&arm.body), + Some(arm.body), arm_ty, |err| self.suggest_removing_semicolon_for_coerce(err, expr, arm_ty, prior_arm), false, diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 173186e6d9f1..d40ac59baa41 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -649,7 +649,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::ExprKind::Path(ref qpath) => { self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id) } - hir::ExprKind::Call(ref inner_callee, _) => { + hir::ExprKind::Call(inner_callee, _) => { if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind { inner_callee_path = Some(inner_qpath); self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id) diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index ee23f47c2711..00af6d462136 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -101,7 +101,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(match *t.kind() { ty::Slice(_) | ty::Str => Some(PointerKind::Length), - ty::Dynamic(ref tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())), + ty::Dynamic(tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())), ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() { None => Some(PointerKind::Thin), Some(f) => { @@ -506,7 +506,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { }; SizedUnsizedCast { - sess: &fcx.tcx.sess, + sess: fcx.tcx.sess, span: self.span, expr_ty: self.expr_ty, cast_ty: fcx.ty_to_string(self.cast_ty), diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 1edc3efbc778..d13ae2c2094c 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -76,7 +76,7 @@ pub(super) fn check_fn<'a, 'tcx>( fcx.resume_yield_tys = Some((resume_ty, yield_ty)); } - GatherLocalsVisitor::new(&fcx).visit_body(body); + GatherLocalsVisitor::new(fcx).visit_body(body); // C-variadic fns also have a `VaList` input that's not listed in `fn_sig` // (as it's created inside the body itself, not passed in from outside). @@ -94,7 +94,7 @@ pub(super) fn check_fn<'a, 'tcx>( for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() { // Check the pattern. let ty_span = try { inputs_hir?.get(idx)?.span }; - fcx.check_pat_top(¶m.pat, param_ty, ty_span, None, None); + fcx.check_pat_top(param.pat, param_ty, ty_span, None, None); // Check that argument is Sized. if !params_can_be_unsized { @@ -123,7 +123,7 @@ pub(super) fn check_fn<'a, 'tcx>( hir::FnRetTy::Return(ty) => ty.span, }; fcx.require_type_is_sized(declared_ret_ty, return_or_body_span, traits::SizedReturnType); - fcx.check_return_expr(&body.value, false); + fcx.check_return_expr(body.value, false); // We insert the deferred_coroutine_interiors entry after visiting the body. // This ensures that all nested coroutines appear before the entry of this coroutine. @@ -156,7 +156,7 @@ pub(super) fn check_fn<'a, 'tcx>( // really expected to fail, since the coercions would have failed // earlier when trying to find a LUB. let coercion = fcx.ret_coercion.take().unwrap().into_inner(); - let mut actual_return_ty = coercion.complete(&fcx); + let mut actual_return_ty = coercion.complete(fcx); debug!("actual_return_ty = {:?}", actual_return_ty); if let ty::Dynamic(..) = declared_ret_ty.kind() { // We have special-cased the case where the function is declared diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 7807ff6547d2..d818bb1dfaa9 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -181,7 +181,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter_instantiated_copied(self.tcx, args) .map(|(c, s)| (c.as_predicate(), s)), ), - ty::Dynamic(ref object_type, ..) => { + ty::Dynamic(object_type, ..) => { let sig = object_type.projection_bounds().find_map(|pb| { let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self); self.deduce_sig_from_projection(None, pb) @@ -630,7 +630,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // First, convert the types that the user supplied (if any). let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a)); let supplied_return = match decl.output { - hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output), + hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(output), hir::FnRetTy::DefaultReturn(_) => match body.coroutine_kind { // In the case of the async block that we create for a function body, // we expect the return type of the block to match that of the enclosing @@ -819,7 +819,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }); if let hir::FnRetTy::Return(ref output) = decl.output { - astconv.ast_ty_to_ty(&output); + astconv.ast_ty_to_ty(output); } let result = ty::Binder::dummy(self.tcx.mk_fn_sig( diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 6c03bc3b57ac..971f10631df4 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -85,7 +85,7 @@ struct Coerce<'a, 'tcx> { impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> { type Target = FnCtxt<'a, 'tcx>; fn deref(&self) -> &Self::Target { - &self.fcx + self.fcx } } @@ -158,7 +158,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { if self.next_trait_solver() { if let Ok(res) = &res { for obligation in &res.obligations { - if !self.predicate_may_hold(&obligation) { + if !self.predicate_may_hold(obligation) { return Err(TypeError::Mismatch); } } @@ -1510,7 +1510,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { expression, expression_ty, ), - Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( + Expressions::UpFront(coercion_sites) => fcx.try_find_coercion_lub( cause, &coercion_sites[0..self.pushed], self.merged_ty(), @@ -1665,7 +1665,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { if visitor.ret_exprs.len() > 0 && let Some(expr) = expression { - self.note_unreachable_loop_return(&mut err, &expr, &visitor.ret_exprs); + self.note_unreachable_loop_return(&mut err, expr, &visitor.ret_exprs); } let reported = err.emit_unless(unsized_return); @@ -1772,7 +1772,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { if blk_id.is_none() { fcx.suggest_missing_return_type( &mut err, - &fn_decl, + fn_decl, expected, found, can_suggest, @@ -1871,6 +1871,6 @@ impl AsCoercionSite for ! { impl AsCoercionSite for hir::Arm<'_> { fn as_coercion_site(&self) -> &hir::Expr<'_> { - &self.body + self.body } } diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 386e4b4642a8..41d88e246af8 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -184,7 +184,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.register_predicates(obligations); None } - Err(e) => Some(self.err_ctxt().report_mismatched_types(&cause, expected, actual, e)), + Err(e) => Some(self.err_ctxt().report_mismatched_types(cause, expected, actual, e)), } } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 4b7de36e7c7b..f74000571ac8 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -277,7 +277,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let tcx = self.tcx; match expr.kind { - ExprKind::Lit(ref lit) => self.check_lit(&lit, expected), + ExprKind::Lit(ref lit) => self.check_lit(lit, expected), ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs, expected), ExprKind::Assign(lhs, rhs, span) => { self.check_expr_assign(expr, expected, lhs, rhs, span) @@ -298,9 +298,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id)); self.check_expr_asm(asm) } - ExprKind::OffsetOf(container, ref fields) => { - self.check_offset_of(container, fields, expr) - } + ExprKind::OffsetOf(container, fields) => self.check_offset_of(container, fields, expr), ExprKind::Break(destination, ref expr_opt) => { self.check_expr_break(destination, expr_opt.as_deref(), expr) } @@ -319,17 +317,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.check_expr_loop(body, source, expected, expr) } ExprKind::Match(discrim, arms, match_src) => { - self.check_match(expr, &discrim, arms, expected, match_src) + self.check_match(expr, discrim, arms, expected, match_src) } ExprKind::Closure(closure) => self.check_expr_closure(closure, expr.span, expected), - ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected), - ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected), + ExprKind::Block(body, _) => self.check_block_with_expected(body, expected), + ExprKind::Call(callee, args) => self.check_call(expr, callee, args, expected), ExprKind::MethodCall(segment, receiver, args, _) => { self.check_method_call(expr, segment, receiver, args, expected) } ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr), ExprKind::Type(e, t) => { - let ascribed_ty = self.to_ty_saving_user_provided_ty(&t); + let ascribed_ty = self.to_ty_saving_user_provided_ty(t); let ty = self.check_expr_with_hint(e, ascribed_ty); self.demand_eqtype(e.span, ascribed_ty, ty); ascribed_ty @@ -347,7 +345,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ExprKind::Struct(qpath, fields, ref base_expr) => { self.check_expr_struct(expr, expected, qpath, fields, base_expr) } - ExprKind::Field(base, field) => self.check_field(expr, &base, field, expected), + ExprKind::Field(base, field) => self.check_field(expr, base, field, expected), ExprKind::Index(base, idx, brackets_span) => { self.check_expr_index(base, idx, expr, brackets_span) } @@ -368,7 +366,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::UnOp::Not | hir::UnOp::Neg => expected, hir::UnOp::Deref => NoExpectation, }; - let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner); + let mut oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner); if !oprnd_t.references_error() { oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t); @@ -436,7 +434,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }); let ty = - self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl)); + self.check_expr_with_expectation_and_needs(oprnd, hint, Needs::maybe_mut_place(mutbl)); let tm = ty::TypeAndMut { ty, mutbl }; match kind { @@ -663,7 +661,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; if let Some(ref mut coerce) = ctxt.coerce { - if let Some(ref e) = expr_opt { + if let Some(e) = expr_opt { coerce.coerce(self, &cause, e, e_ty); } else { assert!(e_ty.is_unit()); @@ -671,12 +669,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { coerce.coerce_forced_unit( self, &cause, - |mut err| { - self.suggest_mismatched_types_on_tail( - &mut err, expr, ty, e_ty, target_id, - ); + |err| { + self.suggest_mismatched_types_on_tail(err, expr, ty, e_ty, target_id); let error = Some(Sorts(ExpectedFound { expected: ty, found: e_ty })); - self.annotate_loop_expected_due_to_inference(&mut err, expr, error); + self.annotate_loop_expected_due_to_inference(err, expr, error); if let Some(val) = ty_kind_suggestion(ty) { err.span_suggestion_verbose( expr.span.shrink_to_hi(), @@ -1136,8 +1132,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // The likely cause of this is `if foo = bar { .. }`. let actual_ty = Ty::new_unit(self.tcx); let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap(); - let lhs_ty = self.check_expr(&lhs); - let rhs_ty = self.check_expr(&rhs); + let lhs_ty = self.check_expr(lhs); + let rhs_ty = self.check_expr(rhs); let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) { (Applicability::MachineApplicable, true) } else if let ExprKind::Binary( @@ -1148,7 +1144,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // if x == 1 && y == 2 { .. } // + - let actual_lhs_ty = self.check_expr(&rhs_expr); + let actual_lhs_ty = self.check_expr(rhs_expr); (Applicability::MaybeIncorrect, self.can_coerce(rhs_ty, actual_lhs_ty)) } else if let ExprKind::Binary( Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. }, @@ -1158,7 +1154,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // if x == 1 && y == 2 { .. } // + - let actual_rhs_ty = self.check_expr(&lhs_expr); + let actual_rhs_ty = self.check_expr(lhs_expr); (Applicability::MaybeIncorrect, self.can_coerce(actual_rhs_ty, lhs_ty)) } else { (Applicability::MaybeIncorrect, false) @@ -1195,7 +1191,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return Ty::new_error(self.tcx, reported); } - let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace); + let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace); let suggest_deref_binop = |err: &mut Diagnostic, rhs_ty: Ty<'tcx>| { if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) { @@ -1222,7 +1218,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // This is (basically) inlined `check_expr_coercible_to_type`, but we want // to suggest an additional fixup here in `suggest_deref_binop`. - let rhs_ty = self.check_expr_with_hint(&rhs, lhs_ty); + let rhs_ty = self.check_expr_with_hint(rhs, lhs_ty); if let (_, Some(mut diag)) = self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No) { @@ -1283,7 +1279,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || { - self.check_block_no_value(&body); + self.check_block_no_value(body); }); if ctxt.may_break { @@ -1313,7 +1309,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { args: &'tcx [hir::Expr<'tcx>], expected: Expectation<'tcx>, ) -> Ty<'tcx> { - let rcvr_t = self.check_expr(&rcvr); + let rcvr_t = self.check_expr(rcvr); // no need to check for bot/err -- callee does that let rcvr_t = self.structurally_resolve_type(rcvr.span, rcvr_t); let span = segment.ident.span; @@ -1347,7 +1343,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Call the generic checker. - self.check_method_argument_types(span, expr, method, &args, DontTupleArguments, expected) + self.check_method_argument_types(span, expr, method, args, DontTupleArguments, expected) } fn check_expr_cast( @@ -1478,7 +1474,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let fcx = FnCtxt::new(self, self.param_env, def_id); crate::GatherLocalsVisitor::new(&fcx).visit_body(body); - let ty = fcx.check_expr_with_expectation(&body.value, expected); + let ty = fcx.check_expr_with_expectation(body.value, expected); fcx.require_type_is_sized(ty, body.value.span, traits::ConstSized); fcx.write_ty(block.hir_id, ty); ty @@ -1507,7 +1503,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (element_ty, t) = match uty { Some(uty) => { - self.check_expr_coercible_to_type(&element, uty, None); + self.check_expr_coercible_to_type(element, uty, None); (uty, uty) } None => { @@ -1515,7 +1511,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { kind: TypeVariableOriginKind::MiscVariable, span: element.span, }); - let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {}); + let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {}); (element_ty, ty) } }; @@ -1611,10 +1607,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds { Some(fs) if i < fs.len() => { let ety = fs[i]; - self.check_expr_coercible_to_type(&e, ety, None); + self.check_expr_coercible_to_type(e, ety, None); ety } - _ => self.check_expr_with_expectation(&e, NoExpectation), + _ => self.check_expr_with_expectation(e, NoExpectation), }); let tuple = Ty::new_tup_from_iter(self.tcx, elt_ts_iter); if let Err(guar) = tuple.error_reported() { @@ -1740,9 +1736,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Make sure to give a type to the field even if there's // an error, so we can continue type-checking. - let ty = self.check_expr_with_hint(&field.expr, field_type); + let ty = self.check_expr_with_hint(field.expr, field_type); let (_, diag) = - self.demand_coerce_diag(&field.expr, ty, field_type, None, AllowTwoPhase::No); + self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No); if let Some(mut diag) = diag { if idx == ast_fields.len() - 1 { @@ -1920,10 +1916,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, ) { for field in fields { - self.check_expr(&field.expr); + self.check_expr(field.expr); } if let Some(base) = *base_expr { - self.check_expr(&base); + self.check_expr(base); } } @@ -2952,8 +2948,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &'tcx hir::Expr<'tcx>, brackets_span: Span, ) -> Ty<'tcx> { - let base_t = self.check_expr(&base); - let idx_t = self.check_expr(&idx); + let base_t = self.check_expr(base); + let idx_t = self.check_expr(idx); if base_t.references_error() { base_t @@ -2994,7 +2990,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut needs_note = true; // If the index is an integer, we can show the actual // fixed expression: - if let ExprKind::Lit(ref lit) = idx.kind + if let ExprKind::Lit(lit) = idx.kind && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node && i < types .len() @@ -3161,7 +3157,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { match self.resume_yield_tys { Some((resume_ty, yield_ty)) => { - self.check_expr_coercible_to_type(&value, yield_ty, None); + self.check_expr_coercible_to_type(value, yield_ty, None); resume_ty } @@ -3170,7 +3166,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // information. Hence, we check the source of the yield expression here and check its // value's type against `()` (this check should always hold). None if src.is_await() => { - self.check_expr_coercible_to_type(&value, Ty::new_unit(self.tcx), None); + self.check_expr_coercible_to_type(value, Ty::new_unit(self.tcx), None); Ty::new_unit(self.tcx) } _ => { diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 6be3ad6577bd..587638f958a4 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -147,7 +147,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.walk_irrefutable_pat(¶m_place, param.pat); } - self.consume_expr(&body.value); + self.consume_expr(body.value); } fn tcx(&self) -> TyCtxt<'tcx> { @@ -237,10 +237,10 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.consume_exprs(exprs); } - hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => { + hir::ExprKind::If(cond_expr, then_expr, ref opt_else_expr) => { self.consume_expr(cond_expr); self.consume_expr(then_expr); - if let Some(ref else_expr) = *opt_else_expr { + if let Some(else_expr) = *opt_else_expr { self.consume_expr(else_expr); } } @@ -249,7 +249,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.walk_local(init, pat, None, |t| t.borrow_expr(init, ty::ImmBorrow)) } - hir::ExprKind::Match(ref discr, arms, _) => { + hir::ExprKind::Match(discr, arms, _) => { let discr_place = return_if_err!(self.mc.cat_expr(discr)); return_if_err!(self.maybe_read_scrutinee( discr, @@ -267,7 +267,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.consume_exprs(exprs); } - hir::ExprKind::AddrOf(_, m, ref base) => { + hir::ExprKind::AddrOf(_, m, base) => { // &base // make sure that the thing we are pointing out stays valid // for the lifetime `scope_r` of the resulting ptr: @@ -379,7 +379,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // only the fn body we were given. } - hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => { + hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr) => { self.consume_expr(expr); } } @@ -505,7 +505,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { )); self.walk_block(els) } - self.walk_irrefutable_pat(&expr_place, &pat); + self.walk_irrefutable_pat(&expr_place, pat); } /// Indicates that the value of `blk` will be consumed, meaning either copied or moved @@ -517,7 +517,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.walk_stmt(stmt); } - if let Some(ref tail_expr) = blk.expr { + if let Some(tail_expr) = blk.expr { self.consume_expr(tail_expr); } } @@ -665,8 +665,8 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.walk_pat(discr_place, arm.pat, arm.guard.is_some()); match arm.guard { - Some(hir::Guard::If(ref e)) => self.consume_expr(e), - Some(hir::Guard::IfLet(ref l)) => { + Some(hir::Guard::If(e)) => self.consume_expr(e), + Some(hir::Guard::IfLet(l)) => { self.walk_local(l.init, l.pat, None, |t| t.borrow_expr(l.init, ty::ImmBorrow)) } None => {} diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 750ed2c34913..551ea1ee11be 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -505,7 +505,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(in super::super) fn resolve_rvalue_scopes(&self, def_id: DefId) { let scope_tree = self.tcx.region_scope_tree(def_id); - let rvalue_scopes = { rvalue_scopes::resolve_rvalue_scopes(self, &scope_tree, def_id) }; + let rvalue_scopes = { rvalue_scopes::resolve_rvalue_scopes(self, scope_tree, def_id) }; let mut typeck_results = self.inh.typeck_results.borrow_mut(); typeck_results.rvalue_scopes = rvalue_scopes; } @@ -804,7 +804,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { qpath, hir_id, span ); let (ty, qself, item_segment) = match *qpath { - QPath::Resolved(ref opt_qself, ref path) => { + QPath::Resolved(ref opt_qself, path) => { return ( path.res, opt_qself.as_ref().map(|qself| self.to_ty(qself)), @@ -1186,7 +1186,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { tcx, span, def_id, - &generics, + generics, seg, IsMethodCall::No, ); @@ -1278,7 +1278,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // going to infer the arguments for better error messages. if !self.infer_args_for_err.contains(&index) { // Check whether the user has provided generic arguments. - if let Some(ref data) = self.segments[index].args { + if let Some(data) = self.segments[index].args { return (Some(data), self.segments[index].infer_args); } } @@ -1406,7 +1406,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Normalize only after registering type annotations. let args = self.normalize(span, args_raw); - self.add_required_obligations_for_hir(span, def_id, &args, hir_id); + self.add_required_obligations_for_hir(span, def_id, args, hir_id); // Substitute the values for the type parameters into the type of // the referenced item. @@ -1473,7 +1473,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { let param_env = self.param_env; - let bounds = self.instantiate_bounds(span, def_id, &args); + let bounds = self.instantiate_bounds(span, def_id, args); for obligation in traits::predicates_for_generics( |idx, predicate_span| { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index facbeb8badfa..e3aca11fd03a 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -495,7 +495,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Whether it succeeded or failed, it likely made some amount of progress. // In the very worst case, it's just the same `expr` we originally passed in. let expr = match self.blame_specific_expr_if_possible_for_obligation_cause_code( - &error.obligation.cause.code(), + error.obligation.cause.code(), expr, ) { Ok(expr) => expr, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index f31e50fd3521..a02073f30254 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -397,7 +397,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for arg in provided_args.iter().skip(minimum_input_count) { // Make sure we've checked this expr at least once. - let arg_ty = self.check_expr(&arg); + let arg_ty = self.check_expr(arg); // If the function is c-style variadic, we skipped a bunch of arguments // so we need to check those, and write out the types @@ -796,7 +796,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut err = self.err_ctxt().report_and_explain_type_error(trace, *err); self.emit_coerce_suggestions( &mut err, - &provided_args[*provided_idx], + provided_args[*provided_idx], provided_ty, Expectation::rvalue_hint(self, expected_ty) .only_has_type(self) @@ -925,7 +925,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.emit_coerce_suggestions( &mut err, - &provided_args[provided_idx], + provided_args[provided_idx], provided_ty, Expectation::rvalue_hint(self, expected_ty) .only_has_type(self) @@ -1469,7 +1469,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Type check the initializer. if let Some(ref init) = decl.init { - let init_ty = self.check_decl_initializer(decl.hir_id, decl.pat, &init); + let init_ty = self.check_decl_initializer(decl.hir_id, decl.pat, init); self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, init_ty); } @@ -1483,7 +1483,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Type check the pattern. Override if necessary to avoid knock-on errors. - self.check_pat_top(&decl.pat, decl_ty, ty_span, origin_expr, Some(decl.origin)); + self.check_pat_top(decl.pat, decl_ty, ty_span, origin_expr, Some(decl.origin)); let pat_ty = self.node_ty(decl.pat.hir_id); self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, pat_ty); @@ -1525,13 +1525,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::StmtKind::Item(_) => {} hir::StmtKind::Expr(ref expr) => { // Check with expected type of `()`. - self.check_expr_has_type_or_error(&expr, Ty::new_unit(self.tcx), |err| { + self.check_expr_has_type_or_error(expr, Ty::new_unit(self.tcx), |err| { if expr.can_have_side_effects() { self.suggest_semicolon_at_end(expr.span, err); } }); } - hir::StmtKind::Semi(ref expr) => { + hir::StmtKind::Semi(expr) => { self.check_expr(expr); } } @@ -1820,12 +1820,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir_id: hir::HirId, ) -> (Res, RawTy<'tcx>) { match *qpath { - QPath::Resolved(ref maybe_qself, ref path) => { + QPath::Resolved(ref maybe_qself, path) => { let self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself).raw); let ty = self.astconv().res_to_ty(self_ty, path, hir_id, true); (path.res, self.handle_raw_ty(path_span, ty)) } - QPath::TypeRelative(ref qself, ref segment) => { + QPath::TypeRelative(qself, segment) => { let ty = self.to_ty(qself); let result = self @@ -1869,7 +1869,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for (_, node) in self.tcx.hir().parent_iter(hir_id) { match node { hir::Node::Stmt(stmt) => { - if let hir::StmtKind::Semi(ref expr) = stmt.kind { + if let hir::StmtKind::Semi(expr) = stmt.kind { let expr_ty = self.typeck_results.borrow().expr_ty(expr); let return_ty = fn_sig.output(); if !matches!(expr.kind, hir::ExprKind::Ret(..)) @@ -2038,7 +2038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.param_env, trait_ref, ); - match SelectionContext::new(&self).select(&obligation) { + match SelectionContext::new(self).select(&obligation) { Ok(Some(traits::ImplSource::UserDefined(impl_source))) => { Some(impl_source.impl_def_id) } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index bd653e799132..072df1343ce6 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -143,7 +143,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub fn sess(&self) -> &Session { - &self.tcx.sess + self.tcx.sess } /// Creates an `TypeErrCtxt` with a reference to the in-progress @@ -196,7 +196,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> { type Target = Inherited<'tcx>; fn deref(&self) -> &Self::Target { - &self.inh + self.inh } } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index a37a595e4a8d..78e755378f5f 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -79,16 +79,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return false; } if let Some((fn_id, fn_decl, can_suggest)) = self.get_fn_decl(blk_id) { - pointing_at_return_type = self.suggest_missing_return_type( - err, - &fn_decl, - expected, - found, - can_suggest, - fn_id, - ); + pointing_at_return_type = + self.suggest_missing_return_type(err, fn_decl, expected, found, can_suggest, fn_id); self.suggest_missing_break_or_return_expr( - err, expr, &fn_decl, expected, found, blk_id, fn_id, + err, expr, fn_decl, expected, found, blk_id, fn_id, ); } pointing_at_return_type @@ -2139,7 +2133,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// opt.map(|param| { takes_ref(param) }); /// ``` fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Vec<(Span, String)>, &'static str)> { - let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind else { + let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind else { return None; }; @@ -2295,7 +2289,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; if self.can_coerce(ref_ty, expected) { let mut sugg_sp = sp; - if let hir::ExprKind::MethodCall(ref segment, receiver, args, _) = expr.kind { + if let hir::ExprKind::MethodCall(segment, receiver, args, _) = expr.kind { let clone_trait = self.tcx.require_lang_item(LangItem::Clone, Some(segment.ident.span)); if args.is_empty() @@ -2313,7 +2307,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - if let hir::ExprKind::Unary(hir::UnOp::Deref, ref inner) = expr.kind + if let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind && let Some(1) = self.deref_steps(expected, checked_ty) { // We have `*&T`, check if what was expected was `&T`. @@ -2406,11 +2400,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )); } } - ( - hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr), - _, - &ty::Ref(_, checked, _), - ) if self.can_sub(self.param_env, checked, expected) => { + (hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr), _, &ty::Ref(_, checked, _)) + if self.can_sub(self.param_env, checked, expected) => + { let make_sugg = |start: Span, end: BytePos| { // skip `(` for tuples such as `(c) = (&123)`. // make sure we won't suggest like `(c) = 123)` which is incorrect. diff --git a/compiler/rustc_hir_typeck/src/gather_locals.rs b/compiler/rustc_hir_typeck/src/gather_locals.rs index 0ad2c1d92843..0cca779b1560 100644 --- a/compiler/rustc_hir_typeck/src/gather_locals.rs +++ b/compiler/rustc_hir_typeck/src/gather_locals.rs @@ -93,7 +93,7 @@ impl<'a, 'tcx> GatherLocalsVisitor<'a, 'tcx> { fn declare(&mut self, decl: Declaration<'tcx>) { let local_ty = match decl.ty { Some(ref ty) => { - let o_ty = self.fcx.to_ty(&ty); + let o_ty = self.fcx.to_ty(ty); let c_ty = self.fcx.inh.infcx.canonicalize_user_type_annotation(UserType::Ty(o_ty.raw)); diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 46dcc455558b..66a0f4ed9def 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -243,7 +243,7 @@ fn typeck_with_fallback<'tcx>( // Gather locals in statics (because of block expressions). GatherLocalsVisitor::new(&fcx).visit_body(body); - fcx.check_expr_coercible_to_type(&body.value, expected_type, None); + fcx.check_expr_coercible_to_type(body.value, expected_type, None); fcx.write_ty(id, expected_type); }; diff --git a/compiler/rustc_hir_typeck/src/mem_categorization.rs b/compiler/rustc_hir_typeck/src/mem_categorization.rs index 337d12b2d511..b25830675b28 100644 --- a/compiler/rustc_hir_typeck/src/mem_categorization.rs +++ b/compiler/rustc_hir_typeck/src/mem_categorization.rs @@ -304,7 +304,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { ) -> McResult> { let expr_ty = self.expr_ty(expr)?; match expr.kind { - hir::ExprKind::Unary(hir::UnOp::Deref, ref e_base) => { + hir::ExprKind::Unary(hir::UnOp::Deref, e_base) => { if self.typeck_results.is_method_call(expr) { self.cat_overloaded_place(expr, e_base) } else { @@ -313,7 +313,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { } } - hir::ExprKind::Field(ref base, _) => { + hir::ExprKind::Field(base, _) => { let base = self.cat_expr(base)?; debug!(?base); @@ -332,7 +332,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { )) } - hir::ExprKind::Index(ref base, _, _) => { + hir::ExprKind::Index(base, _, _) => { if self.typeck_results.is_method_call(expr) { // If this is an index implemented by a method call, then it // will include an implicit deref of the result. @@ -351,7 +351,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { self.cat_res(expr.hir_id, expr.span, expr_ty, res) } - hir::ExprKind::Type(ref e, _) => self.cat_expr(e), + hir::ExprKind::Type(e, _) => self.cat_expr(e), hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) @@ -728,11 +728,11 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { } } - PatKind::Binding(.., Some(ref subpat)) => { + PatKind::Binding(.., Some(subpat)) => { self.cat_pattern_(place_with_id, subpat, op)?; } - PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => { + PatKind::Box(subpat) | PatKind::Ref(subpat, _) => { // box p1, &p1, &mut p1. we can ignore the mutability of // PatKind::Ref since that information is already contained // in the type. @@ -754,7 +754,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { for before_pat in before { self.cat_pattern_(elt_place.clone(), before_pat, op)?; } - if let Some(ref slice_pat) = *slice { + if let Some(slice_pat) = *slice { let slice_pat_ty = self.pat_ty_adjusted(slice_pat)?; let slice_place = self.cat_projection( pat, diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 7c73f6a89cdb..e7af7da205c6 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -93,16 +93,16 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { segment: &hir::PathSegment<'_>, ) -> ConfirmResult<'tcx> { // Adjust the self expression the user provided and obtain the adjusted type. - let self_ty = self.adjust_self_ty(unadjusted_self_ty, &pick); + let self_ty = self.adjust_self_ty(unadjusted_self_ty, pick); // Create substitutions for the method's type parameters. - let rcvr_args = self.fresh_receiver_args(self_ty, &pick); - let all_args = self.instantiate_method_args(&pick, segment, rcvr_args); + let rcvr_args = self.fresh_receiver_args(self_ty, pick); + let all_args = self.instantiate_method_args(pick, segment, rcvr_args); debug!("rcvr_args={rcvr_args:?}, all_args={all_args:?}"); // Create the final signature for the method, replacing late-bound regions. - let (method_sig, method_predicates) = self.instantiate_method_sig(&pick, all_args); + let (method_sig, method_predicates) = self.instantiate_method_sig(pick, all_args); // If there is a `Self: Sized` bound and `Self` is a trait object, it is possible that // something which derefs to `Self` actually implements the trait and the caller @@ -129,14 +129,14 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { "confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}", self_ty, method_sig_rcvr, method_sig, method_predicates ); - self.unify_receivers(self_ty, method_sig_rcvr, &pick, all_args); + self.unify_receivers(self_ty, method_sig_rcvr, pick, all_args); let (method_sig, method_predicates) = self.normalize(self.span, (method_sig, method_predicates)); let method_sig = ty::Binder::dummy(method_sig); // Make sure nobody calls `drop()` explicitly. - self.enforce_illegal_method_limitations(&pick); + self.enforce_illegal_method_limitations(pick); // Add any trait/regions obligations specified on the method's type parameters. // We won't add these if we encountered an illegal sized bound, so that we can use diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index d2a72f8f2338..9ed18ffe103f 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1135,7 +1135,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { .fcx .probe_instantiate_query_response( self.span, - &self.orig_steps_var_values, + self.orig_steps_var_values, &step.self_ty, ) .unwrap_or_else(|_| { @@ -1509,7 +1509,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // match as well (or at least may match, sometimes we // don't have enough information to fully evaluate). match probe.kind { - InherentImplCandidate(ref args, ref ref_obligations) => { + InherentImplCandidate(args, ref ref_obligations) => { // `xform_ret_ty` hasn't been normalized yet, only `xform_self_ty`, // see the reasons mentioned in the comments in `assemble_inherent_impl_probe` // for why this is necessary diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index db434636f595..3b96cd96d2ed 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -484,7 +484,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.note_internal_mutation_in_method( &mut err, rcvr_expr, - expected.to_option(&self), + expected.to_option(self), rcvr_ty, ); } @@ -509,7 +509,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if static_candidates.len() == 1 { self.suggest_associated_call_syntax( &mut err, - &static_candidates, + static_candidates, rcvr_ty, source, item_name, @@ -969,7 +969,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "the following trait bounds were not satisfied:\n{bound_list}" )); } - self.suggest_derive(&mut err, &unsatisfied_predicates); + self.suggest_derive(&mut err, unsatisfied_predicates); unsatisfied_bounds = true; } @@ -1170,8 +1170,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { args.map(|args| args.len() + 1), source, no_match_data.out_of_scope_traits.clone(), - &unsatisfied_predicates, - &static_candidates, + unsatisfied_predicates, + static_candidates, unsatisfied_bounds, expected.only_has_type(self), trait_missing_method, @@ -1722,7 +1722,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for (_, parent) in tcx.hir().parent_iter(expr.hir_id).take(5) { if let Node::Expr(parent_expr) = parent { let lang_item = match parent_expr.kind { - ExprKind::Struct(ref qpath, _, _) => match **qpath { + ExprKind::Struct(qpath, _, _) => match *qpath { QPath::LangItem(LangItem::Range, ..) => Some(LangItem::Range), QPath::LangItem(LangItem::RangeTo, ..) => Some(LangItem::RangeTo), QPath::LangItem(LangItem::RangeToInclusive, ..) => { @@ -1730,7 +1730,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } _ => None, }, - ExprKind::Call(ref func, _) => match func.kind { + ExprKind::Call(func, _) => match func.kind { // `..=` desugars into `::std::ops::RangeInclusive::new(...)`. ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)) => { Some(LangItem::RangeInclusiveStruct) @@ -1749,7 +1749,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { eps.len() > 0 && eps.last().is_some_and(|ep| ep.span.contains(span)) } // `..=` desugars into `::std::ops::RangeInclusive::new(...)`. - hir::ExprKind::Call(ref func, ..) => func.span.contains(span), + hir::ExprKind::Call(func, ..) => func.span.contains(span), _ => false, }; @@ -1843,7 +1843,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); let concrete_type = if actual.is_integral() { "i32" } else { "f32" }; match expr.kind { - ExprKind::Lit(ref lit) => { + ExprKind::Lit(lit) => { // numeric literal let snippet = tcx .sess @@ -1947,7 +1947,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let mut visitor = LetVisitor { result: None, ident_name: seg1.ident.name }; - visitor.visit_body(&body); + visitor.visit_body(body); let parent = self.tcx.hir().parent_id(seg1.hir_id); if let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index b30f9b82fbbf..f11ffabf4d4d 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -872,7 +872,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.demand_eqtype_pat(pat.span, expected, pat_ty, pat_info.top_info); // Type-check subpatterns. - if self.check_struct_pat_fields(pat_ty, &pat, variant, fields, has_rest_pat, pat_info) { + if self.check_struct_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info) { pat_ty } else { Ty::new_misc_error(self.tcx) diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index 406434e09e68..f8ca3a4f3d7c 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -283,9 +283,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Gather up expressions we want to munge. let mut exprs = vec![expr]; - while let hir::ExprKind::Field(ref expr, _) - | hir::ExprKind::Index(ref expr, _, _) - | hir::ExprKind::Unary(hir::UnOp::Deref, ref expr) = exprs.last().unwrap().kind + while let hir::ExprKind::Field(expr, _) + | hir::ExprKind::Index(expr, _, _) + | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = exprs.last().unwrap().kind { exprs.push(expr); } diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 1b160eca92db..3f30b3f2b4c0 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -231,13 +231,13 @@ fn dump_graph(query: &DepGraphQuery) { // Expect one of: "-> target", "source -> target", or "source ->". let edge_filter = EdgeFilter::new(&string).unwrap_or_else(|e| bug!("invalid filter: {}", e)); - let sources = node_set(&query, &edge_filter.source); - let targets = node_set(&query, &edge_filter.target); - filter_nodes(&query, &sources, &targets) + let sources = node_set(query, &edge_filter.source); + let targets = node_set(query, &edge_filter.target); + filter_nodes(query, &sources, &targets) } Err(_) => query.nodes().into_iter().map(|n| n.kind).collect(), }; - let edges = filter_edges(&query, &nodes); + let edges = filter_edges(query, &nodes); { // dump a .txt file with just the edges: diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 5dd06c6ca4f4..eaf83b7ee5f4 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -378,15 +378,15 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { }; self.checked_attrs.insert(attr.id); for label in assertion.clean.items().into_sorted_stable_ord() { - let dep_node = DepNode::from_label_string(self.tcx, &label, def_path_hash).unwrap(); + let dep_node = DepNode::from_label_string(self.tcx, label, def_path_hash).unwrap(); self.assert_clean(item_span, dep_node); } for label in assertion.dirty.items().into_sorted_stable_ord() { - let dep_node = DepNode::from_label_string(self.tcx, &label, def_path_hash).unwrap(); + let dep_node = DepNode::from_label_string(self.tcx, label, def_path_hash).unwrap(); self.assert_dirty(item_span, dep_node); } for label in assertion.loaded_from_disk.items().into_sorted_stable_ord() { - let dep_node = DepNode::from_label_string(self.tcx, &label, def_path_hash).unwrap(); + let dep_node = DepNode::from_label_string(self.tcx, label, def_path_hash).unwrap(); self.assert_loaded_from_disk(item_span, dep_node); } } diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index f56fb0d0534b..2d809030e583 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -499,7 +499,7 @@ fn lock_directory( } fn delete_session_dir_lock_file(sess: &Session, lock_file_path: &Path) { - if let Err(err) = safe_remove_file(&lock_file_path) { + if let Err(err) = safe_remove_file(lock_file_path) { sess.emit_warning(errors::DeleteLock { path: lock_file_path, err }); } } @@ -847,10 +847,10 @@ pub(crate) fn garbage_collect_session_directories(sess: &Session) -> io::Result< fn delete_old(sess: &Session, path: &Path) { debug!("garbage_collect_session_directories() - deleting `{}`", path.display()); - if let Err(err) = safe_remove_dir_all(&path) { - sess.emit_warning(errors::SessionGcFailed { path: &path, err }); + if let Err(err) = safe_remove_dir_all(path) { + sess.emit_warning(errors::SessionGcFailed { path: path, err }); } else { - delete_session_dir_lock_file(sess, &lock_file_path(&path)); + delete_session_dir_lock_file(sess, &lock_file_path(path)); } } diff --git a/compiler/rustc_incremental/src/persist/load.rs b/compiler/rustc_incremental/src/persist/load.rs index 6dfc40969106..f2c1d0b83aac 100644 --- a/compiler/rustc_incremental/src/persist/load.rs +++ b/compiler/rustc_incremental/src/persist/load.rs @@ -99,7 +99,7 @@ fn load_dep_graph(sess: &Session) -> LoadResult<(SerializedDepGraph, WorkProduct // Calling `sess.incr_comp_session_dir()` will panic if `sess.opts.incremental.is_none()`. // Fortunately, we just checked that this isn't the case. - let path = dep_graph_path(&sess); + let path = dep_graph_path(sess); let expected_hash = sess.opts.dep_tracking_hash(false); let mut prev_work_products = UnordMap::default(); diff --git a/compiler/rustc_incremental/src/persist/work_product.rs b/compiler/rustc_incremental/src/persist/work_product.rs index fb96bed5a718..1ee3d13922b4 100644 --- a/compiler/rustc_incremental/src/persist/work_product.rs +++ b/compiler/rustc_incremental/src/persist/work_product.rs @@ -31,7 +31,7 @@ pub fn copy_cgu_workproduct_to_incr_comp_cache_dir( } Err(err) => { sess.emit_warning(errors::CopyWorkProductToCache { - from: &path, + from: path, to: &path_in_incr_dir, err, }); diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index d911e28484c2..6860d0de179e 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -552,7 +552,7 @@ impl<'tcx> InferCtxt<'tcx> { // `query_response.var_values` after applying the substitution // `result_subst`. let substituted_query_response = |index: BoundVar| -> GenericArg<'tcx> { - query_response.substitute_projected(self.tcx, &result_subst, |v| v.var_values[index]) + query_response.substitute_projected(self.tcx, result_subst, |v| v.var_values[index]) }; // Unify the original value for each variable with the value diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index d7669b1a4b55..a2aa99e78e1e 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -155,7 +155,7 @@ impl TypeErrCtxt<'_, '_> { impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx> { type Target = InferCtxt<'tcx>; fn deref(&self) -> &InferCtxt<'tcx> { - &self.infcx + self.infcx } } @@ -1019,8 +1019,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { /// ``` fn cmp_type_arg( &self, - mut t1_out: &mut DiagnosticStyledString, - mut t2_out: &mut DiagnosticStyledString, + t1_out: &mut DiagnosticStyledString, + t2_out: &mut DiagnosticStyledString, path: String, sub: &'tcx [ty::GenericArg<'tcx>], other_path: String, @@ -1031,13 +1031,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let sub = self.tcx.mk_args(sub); for (i, ta) in sub.types().enumerate() { if ta == other_ty { - self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty); + self.highlight_outer(t1_out, t2_out, path, sub, i, other_ty); return Some(()); } if let ty::Adt(def, _) = ta.kind() { let path_ = self.tcx.def_path_str(def.did()); if path_ == other_path { - self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty); + self.highlight_outer(t1_out, t2_out, path, sub, i, other_ty); return Some(()); } } 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 4beb51da72ce..034b9795bf8d 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 @@ -419,7 +419,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { return self.bad_inference_failure_err(failure_span, arg_data, error_code); }; - let mut local_visitor = FindInferSourceVisitor::new(&self, typeck_results, arg); + let mut local_visitor = FindInferSourceVisitor::new(self, typeck_results, arg); if let Some(body_id) = self.tcx.hir().maybe_body_owned_by( self.tcx.typeck_root_def_id(body_def_id.to_def_id()).expect_local(), ) { diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs index 0df417d09501..5687d85d24a3 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs @@ -96,7 +96,7 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> { } } - hir::TyKind::Ref(ref lifetime, _) => { + hir::TyKind::Ref(lifetime, _) => { // the lifetime of the Ref let hir_id = lifetime.hir_id; match (self.tcx.named_bound_var(hir_id), self.bound_region) { diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs index 6901955af65f..df7907e1fd3a 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs @@ -81,7 +81,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { for matching_def_id in v.0 { let mut hir_v = super::static_impl_trait::HirTraitObjectVisitor(&mut traits, matching_def_id); - hir_v.visit_ty(&impl_self_ty); + hir_v.visit_ty(impl_self_ty); } if traits.is_empty() { diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index e2be6cf4280a..81154415c1e5 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -78,7 +78,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { has_impl_path, impl_path, }); - if self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt) { + if self.find_impl_on_dyn_trait(&mut err, param.param_ty, ctxt) { let reported = err.emit(); return Some(reported); } else { @@ -204,7 +204,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { && let ObligationCauseCode::UnifyReceiver(ctxt) = cause.code() // Handle case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a // `'static` lifetime when called as a method on a binding: `bar.qux()`. - && self.find_impl_on_dyn_trait(&mut err, param.param_ty, &ctxt) + && self.find_impl_on_dyn_trait(&mut err, param.param_ty, ctxt) { override_error_code = Some(ctxt.assoc_item.name); } @@ -530,7 +530,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { for found_did in found_dids { let mut traits = vec![]; let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did); - hir_v.visit_ty(&self_ty); + hir_v.visit_ty(self_ty); for &span in &traits { let subdiag = DynTraitConstraintSuggestion { span, ident }; subdiag.add_to_diagnostic(err); diff --git a/compiler/rustc_infer/src/infer/error_reporting/note.rs b/compiler/rustc_infer/src/infer/error_reporting/note.rs index 8d3cd23b7fa5..781cc192ae55 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note.rs @@ -63,7 +63,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { .add_to_diagnostic(err); } infer::CheckAssociatedTypeBounds { ref parent, .. } => { - self.note_region_origin(err, &parent); + self.note_region_origin(err, parent); } infer::AscribeUserTypeProvePredicate(span) => { RegionOriginNote::Plain { diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index f0b33d30e2c6..aa5fe6d3f56c 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -511,7 +511,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } let mut visitor = IfVisitor { err_span: span, found_if: false, result: false }; - visitor.visit_body(&body); + visitor.visit_body(body); if visitor.result { return Some(TypeErrorAdditionalDiags::AddLetForLetChains { span: span.shrink_to_lo(), @@ -636,10 +636,10 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { return None; } let last_stmt = blk.stmts.last()?; - let hir::StmtKind::Semi(ref last_expr) = last_stmt.kind else { + let hir::StmtKind::Semi(last_expr) = last_stmt.kind else { return None; }; - let last_expr_ty = self.typeck_results.as_ref()?.expr_ty_opt(*last_expr)?; + let last_expr_ty = self.typeck_results.as_ref()?.expr_ty_opt(last_expr)?; let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) { _ if last_expr_ty.references_error() => return None, _ if self.same_type_modulo_infer(last_expr_ty, expected_ty) => { diff --git a/compiler/rustc_infer/src/infer/opaque_types.rs b/compiler/rustc_infer/src/infer/opaque_types.rs index 7a792d30cc74..4e2cd00613b0 100644 --- a/compiler/rustc_infer/src/infer/opaque_types.rs +++ b/compiler/rustc_infer/src/infer/opaque_types.rs @@ -447,7 +447,7 @@ where } match ty.kind() { - ty::Closure(_, ref args) => { + ty::Closure(_, args) => { // Skip lifetime parameters of the enclosing item(s) for upvar in args.as_closure().upvar_tys() { @@ -456,7 +456,7 @@ where args.as_closure().sig_as_fn_ptr_ty().visit_with(self); } - ty::Coroutine(_, ref args, _) => { + ty::Coroutine(_, args, _) => { // Skip lifetime parameters of the enclosing item(s) // Also skip the witness type, because that has no free regions. @@ -468,7 +468,7 @@ where args.as_coroutine().resume_ty().visit_with(self); } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, ref args, .. }) => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // Skip lifetime parameters that are not captures. let variances = self.tcx.variances_of(*def_id); @@ -575,7 +575,7 @@ impl<'tcx> InferCtxt<'tcx> { .register(opaque_type_key, OpaqueHiddenType { ty: hidden_ty, span }); if let Some(prev) = prev { obligations.extend( - self.at(&cause, param_env) + self.at(cause, param_env) .eq_exp(DefineOpaqueTypes::Yes, a_is_expected, prev, hidden_ty)? .obligations, ); diff --git a/compiler/rustc_infer/src/infer/outlives/components.rs b/compiler/rustc_infer/src/infer/outlives/components.rs index 806ecf35330f..45df22d44e81 100644 --- a/compiler/rustc_infer/src/infer/outlives/components.rs +++ b/compiler/rustc_infer/src/infer/outlives/components.rs @@ -98,12 +98,12 @@ fn compute_components<'tcx>( compute_components(tcx, element, out, visited); } - ty::Closure(_, ref args) => { + ty::Closure(_, args) => { let tupled_ty = args.as_closure().tupled_upvars_ty(); compute_components(tcx, tupled_ty, out, visited); } - ty::Coroutine(_, ref args, _) => { + ty::Coroutine(_, args, _) => { // Same as the closure case let tupled_ty = args.as_coroutine().tupled_upvars_ty(); compute_components(tcx, tupled_ty, out, visited); diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 1bc24682b9ac..c6cbde4dba98 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -136,7 +136,7 @@ impl<'tcx> InferCtxt<'tcx> { let outlives = &mut TypeOutlives::new( self, self.tcx, - &outlives_env.region_bound_pairs(), + outlives_env.region_bound_pairs(), None, outlives_env.param_env, ); @@ -248,7 +248,7 @@ where } Component::Alias(alias_ty) => self.alias_ty_must_outlive(origin, region, *alias_ty), Component::EscapingAlias(subcomponents) => { - self.components_must_outlive(origin, &subcomponents, region, category); + self.components_must_outlive(origin, subcomponents, region, category); } Component::UnresolvedInferenceVariable(v) => { // ignore this, we presume it will yield an error diff --git a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs index b6ff8f2f512d..479343c3ec28 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs @@ -81,7 +81,7 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> { return Ok(()); } - let mini_graph = &MiniGraph::new(tcx, &self, only_consider_snapshot); + let mini_graph = &MiniGraph::new(tcx, self, only_consider_snapshot); let mut leak_check = LeakCheck::new(tcx, outer_universe, max_universe, mini_graph, self); leak_check.assign_placeholder_values()?; diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 0baf77c4f7e1..ec024dac8ddb 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -127,7 +127,7 @@ fn configure_and_expand( let tcx = resolver.tcx(); let sess = tcx.sess; let features = tcx.features(); - let lint_store = unerased_lint_store(&tcx.sess); + let lint_store = unerased_lint_store(tcx.sess); let crate_name = tcx.crate_name(LOCAL_CRATE); let lint_check_node = (&krate, pre_configured_attrs); pre_expansion_lint( @@ -150,7 +150,7 @@ fn configure_and_expand( ) }); - util::check_attr_crate_type(sess, pre_configured_attrs, &mut resolver.lint_buffer()); + util::check_attr_crate_type(sess, pre_configured_attrs, resolver.lint_buffer()); // Expand all macros krate = sess.time("macro_expand_crate", || { @@ -284,16 +284,16 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { let mut lint_buffer = resolver.lint_buffer.steal(); if sess.opts.unstable_opts.input_stats { - eprintln!("Post-expansion node count: {}", count_nodes(&krate)); + eprintln!("Post-expansion node count: {}", count_nodes(krate)); } if sess.opts.unstable_opts.hir_stats { - hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS", "ast-stats-2"); + hir_stats::print_ast_stats(krate, "POST EXPANSION AST STATS", "ast-stats-2"); } // Needs to go *after* expansion to be able to check the results of macro expansion. sess.time("complete_gated_feature_checking", || { - rustc_ast_passes::feature_gate::check_crate(&krate, sess, tcx.features()); + rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features()); }); // Add all buffered lints from the `ParseSess` to the `Session`. @@ -319,7 +319,7 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { } }); - let lint_store = unerased_lint_store(&tcx.sess); + let lint_store = unerased_lint_store(tcx.sess); rustc_lint::check_ast_node( sess, tcx.features(), @@ -521,11 +521,11 @@ fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[P if sess.opts.json_artifact_notifications { sess.parse_sess .span_diagnostic - .emit_artifact_notification(&deps_filename, "dep-info"); + .emit_artifact_notification(deps_filename, "dep-info"); } } Err(error) => { - sess.emit_fatal(errors::ErrorWritingDependencies { path: &deps_filename, error }); + sess.emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error }); } } } @@ -564,12 +564,12 @@ fn output_filenames(tcx: TyCtxt<'_>, (): ()) -> Arc { generated_output_paths(tcx, &outputs, sess.io.output_file.is_some(), crate_name); // Ensure the source file isn't accidentally overwritten during compilation. - if let Some(ref input_path) = sess.io.input.opt_path() { + if let Some(input_path) = sess.io.input.opt_path() { if sess.opts.will_create_output_file() { if output_contains_path(&output_paths, input_path) { sess.emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path }); } - if let Some(ref dir_path) = output_conflicts_with_dir(&output_paths) { + if let Some(dir_path) = output_conflicts_with_dir(&output_paths) { sess.emit_fatal(errors::GeneratedFileConflictsWithDirectory { input_path, dir_path, diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index fbf2dbcdae50..3fee2d289818 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -102,7 +102,7 @@ impl<'tcx> Queries<'tcx> { } fn session(&self) -> &Session { - &self.compiler.session() + self.compiler.session() } fn codegen_backend(&self) -> &dyn CodegenBackend { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index b434659f0d5c..a1c5cfacc82b 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -263,7 +263,7 @@ impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns { continue; } if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind { - if cx.tcx.find_field_index(ident, &variant) + if cx.tcx.find_field_index(ident, variant) == Some(cx.typeck_results().field_index(fieldpat.hir_id)) { cx.emit_spanned_lint( @@ -633,21 +633,21 @@ impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { return; } let (def, ty) = match item.kind { - hir::ItemKind::Struct(_, ref ast_generics) => { + hir::ItemKind::Struct(_, ast_generics) => { if !ast_generics.params.is_empty() { return; } let def = cx.tcx.adt_def(item.owner_id); (def, Ty::new_adt(cx.tcx, def, ty::List::empty())) } - hir::ItemKind::Union(_, ref ast_generics) => { + hir::ItemKind::Union(_, ast_generics) => { if !ast_generics.params.is_empty() { return; } let def = cx.tcx.adt_def(item.owner_id); (def, Ty::new_adt(cx.tcx, def, ty::List::empty())) } - hir::ItemKind::Enum(_, ref ast_generics) => { + hir::ItemKind::Enum(_, ast_generics) => { if !ast_generics.params.is_empty() { return; } @@ -1027,7 +1027,7 @@ impl EarlyLintPass for UnusedDocComment { } fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) { - warn_if_doc(cx, block.span, "blocks", &block.attrs()); + warn_if_doc(cx, block.span, "blocks", block.attrs()); } fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { @@ -1117,7 +1117,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { } }; match it.kind { - hir::ItemKind::Fn(.., ref generics, _) => { + hir::ItemKind::Fn(.., generics, _) => { if let Some(no_mangle_attr) = attr::find_by_name(attrs, sym::no_mangle) { check_no_mangle_on_generic_fn(no_mangle_attr, None, generics, it.span); } @@ -1444,10 +1444,10 @@ declare_lint_pass!( impl TypeAliasBounds { pub(crate) fn is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool { match *qpath { - hir::QPath::TypeRelative(ref ty, _) => { + hir::QPath::TypeRelative(ty, _) => { // If this is a type variable, we found a `T::Assoc`. match ty.kind { - hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => { + hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { matches!(path.res, Res::Def(DefKind::TyParam, _)) } _ => false, @@ -1714,16 +1714,16 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns { } let (parentheses, endpoints) = match &pat.kind { - PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)), + PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(subpat)), _ => (false, matches_ellipsis_pat(pat)), }; if let Some((start, end, join)) = endpoints { if parentheses { self.node_id = Some(pat.id); - let end = expr_to_string(&end); + let end = expr_to_string(end); let replace = match start { - Some(start) => format!("&({}..={})", expr_to_string(&start), end), + Some(start) => format!("&({}..={})", expr_to_string(start), end), None => format!("&(..={end})"), }; if join.edition() >= Edition::Edition2021 { @@ -2381,7 +2381,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { /// Determine if this expression is a "dangerous initialization". fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option { - if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind { + if let hir::ExprKind::Call(path_expr, args) = expr.kind { // Find calls to `mem::{uninitialized,zeroed}` methods. if let hir::ExprKind::Path(ref qpath) = path_expr.kind { let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; @@ -2398,7 +2398,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) { // This is a call to *some* method named `assume_init`. // See if the `self` parameter is one of the dangerous constructors. - if let hir::ExprKind::Call(ref path_expr, _) = receiver.kind { + if let hir::ExprKind::Call(path_expr, _) = receiver.kind { if let hir::ExprKind::Path(ref qpath) = path_expr.kind { let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; match cx.tcx.get_diagnostic_name(def_id) { @@ -2540,7 +2540,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { return variant_find_init_error( cx, ty, - &first_variant.0, + first_variant.0, args, "field of the only potentially inhabited enum variant", init, @@ -2646,13 +2646,13 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { /// test if expression is a null ptr fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { match &expr.kind { - rustc_hir::ExprKind::Cast(ref expr, ref ty) => { + rustc_hir::ExprKind::Cast(expr, ty) => { if let rustc_hir::TyKind::Ptr(_) = ty.kind { return is_zero(expr) || is_null_ptr(cx, expr); } } // check for call to `core::ptr::null` or `core::ptr::null_mut` - rustc_hir::ExprKind::Call(ref path, _) => { + rustc_hir::ExprKind::Call(path, _) => { if let rustc_hir::ExprKind::Path(ref qpath) = path.kind { if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() { return matches!( @@ -2670,7 +2670,7 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { /// test if expression is the literal `0` fn is_zero(expr: &hir::Expr<'_>) -> bool { match &expr.kind { - rustc_hir::ExprKind::Lit(ref lit) => { + rustc_hir::ExprKind::Lit(lit) => { if let LitKind::Int(a, _) = lit.node { return a == 0; } diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index d500c3b66d66..f427b77d65ce 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -385,7 +385,7 @@ impl LintStore { }; } Some(LintGroup { lint_ids, .. }) => { - return CheckLintNameResult::Tool(Ok(&lint_ids)); + return CheckLintNameResult::Tool(Ok(lint_ids)); } }, Some(Id(id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))), @@ -406,12 +406,12 @@ impl LintStore { if let Some(LintAlias { name, silent }) = depr { let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap(); return if *silent { - CheckLintNameResult::Ok(&lint_ids) + CheckLintNameResult::Ok(lint_ids) } else { - CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string()))) + CheckLintNameResult::Tool(Err((Some(lint_ids), (*name).to_string()))) }; } - CheckLintNameResult::Ok(&lint_ids) + CheckLintNameResult::Ok(lint_ids) } }, Some(Id(id)) => CheckLintNameResult::Ok(slice::from_ref(id)), @@ -458,12 +458,12 @@ impl LintStore { if let Some(LintAlias { name, silent }) = depr { let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap(); return if *silent { - CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name))) + CheckLintNameResult::Tool(Err((Some(lint_ids), complete_name))) } else { - CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string()))) + CheckLintNameResult::Tool(Err((Some(lint_ids), (*name).to_string()))) }; } - CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name))) + CheckLintNameResult::Tool(Err((Some(lint_ids), complete_name))) } }, Some(Id(id)) => { @@ -1051,7 +1051,7 @@ impl<'a> EarlyContext<'a> { impl<'tcx> LintContext for LateContext<'tcx> { /// Gets the overall compiler `Session` object. fn sess(&self) -> &Session { - &self.tcx.sess + self.tcx.sess } #[rustc_lint_diagnostics] @@ -1080,7 +1080,7 @@ impl<'tcx> LintContext for LateContext<'tcx> { impl LintContext for EarlyContext<'_> { /// Gets the overall compiler `Session` object. fn sess(&self) -> &Session { - &self.builder.sess() + self.builder.sess() } #[rustc_lint_diagnostics] @@ -1127,7 +1127,7 @@ impl<'tcx> LateContext<'tcx> { /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing. pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { match *qpath { - hir::QPath::Resolved(_, ref path) => path.res, + hir::QPath::Resolved(_, path) => path.res, hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self .maybe_typeck_results() .filter(|typeck_results| typeck_results.hir_owner == id.owner) diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index d102e3a6c150..36aa959ddc95 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -350,7 +350,7 @@ impl<'a> EarlyCheckNode<'a> for (&'a ast::Crate, &'a [ast::Attribute]) { where 'a: 'b, { - &self.1 + self.1 } fn check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>) where diff --git a/compiler/rustc_lint/src/expect.rs b/compiler/rustc_lint/src/expect.rs index 740c90757e60..047a214a8b24 100644 --- a/compiler/rustc_lint/src/expect.rs +++ b/compiler/rustc_lint/src/expect.rs @@ -24,7 +24,7 @@ fn check_expectations(tcx: TyCtxt<'_>, tool_filter: Option) { // This check will always be true, since `lint_expectations` only // holds stable ids if let LintExpectationId::Stable { hir_id, .. } = id { - if !fulfilled_expectations.contains(&id) + if !fulfilled_expectations.contains(id) && tool_filter.map_or(true, |filter| expectation.lint_tool == Some(filter)) { let rationale = expectation.reason.map(|rationale| ExpectationNote { rationale }); diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index c8ec0458ba42..ea922785a954 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -137,7 +137,7 @@ fn suggest_question_mark<'tcx>( // Check that the function/closure/constant we are in has a `Result` type. // Otherwise suggesting using `?` may not be a good idea. { - let ty = cx.typeck_results().expr_ty(&cx.tcx.hir().body(body_id).value); + let ty = cx.typeck_results().expr_ty(cx.tcx.hir().body(body_id).value); let ty::Adt(ret_adt, ..) = ty.kind() else { return false }; if !cx.tcx.is_diagnostic_item(sym::Result, ret_adt.did()) { return false; diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 2d86129c480c..823ede1222c8 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -196,7 +196,7 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { } } else if !ty.span.from_expansion() && path.segments.len() > 1 - && let Some(ty) = is_ty_or_ty_ctxt(cx, &path) + && let Some(ty) = is_ty_or_ty_ctxt(cx, path) { cx.emit_spanned_lint( USAGE_OF_QUALIFIED_TY, diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index 10c4c0dc79f9..551fe23f9f19 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -279,7 +279,7 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { let generics = self.context.generics.take(); - self.context.generics = Some(&trait_item.generics); + self.context.generics = Some(trait_item.generics); self.with_lint_attrs(trait_item.hir_id(), |cx| { cx.with_param_env(trait_item.owner_id, |cx| { lint_callback!(cx, check_trait_item, trait_item); @@ -291,7 +291,7 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { let generics = self.context.generics.take(); - self.context.generics = Some(&impl_item.generics); + self.context.generics = Some(impl_item.generics); self.with_lint_attrs(impl_item.hir_id(), |cx| { cx.with_param_env(impl_item.owner_id, |cx| { lint_callback!(cx, check_impl_item, impl_item); @@ -355,7 +355,7 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( enclosing_body: None, cached_typeck_results: Cell::new(None), param_env: ty::ParamEnv::empty(), - effective_visibilities: &tcx.effective_visibilities(()), + effective_visibilities: tcx.effective_visibilities(()), last_node_with_lint_attrs: tcx.hir().local_def_id_to_hir_id(module_def_id), generics: None, only_module: true, @@ -364,7 +364,7 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( // Note: `passes` is often empty. In that case, it's faster to run // `builtin_lints` directly rather than bundling it up into the // `RuntimeCombinedLateLintPass`. - let mut passes: Vec<_> = unerased_lint_store(&tcx.sess) + let mut passes: Vec<_> = unerased_lint_store(tcx.sess) .late_module_passes .iter() .map(|mk_pass| (mk_pass)(tcx)) @@ -405,7 +405,7 @@ fn late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>( fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) { // Note: `passes` is often empty. let mut passes: Vec<_> = - unerased_lint_store(&tcx.sess).late_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); + unerased_lint_store(tcx.sess).late_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect(); if passes.is_empty() { return; @@ -416,7 +416,7 @@ fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) { enclosing_body: None, cached_typeck_results: Cell::new(None), param_env: ty::ParamEnv::empty(), - effective_visibilities: &tcx.effective_visibilities(()), + effective_visibilities: tcx.effective_visibilities(()), last_node_with_lint_attrs: hir::CRATE_HIR_ID, generics: None, only_module: false, diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index ee5fa87e45db..1281cc9f9203 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -123,7 +123,7 @@ impl LintLevelSets { } fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExpectation)> { - let store = unerased_lint_store(&tcx.sess); + let store = unerased_lint_store(tcx.sess); let mut builder = LintLevelsBuilder { sess: tcx.sess, @@ -138,7 +138,7 @@ fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExp }, warn_about_weird_lints: false, store, - registered_tools: &tcx.registered_tools(()), + registered_tools: tcx.registered_tools(()), }; builder.add_command_line(); @@ -152,7 +152,7 @@ fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExp #[instrument(level = "trace", skip(tcx), ret)] fn shallow_lint_levels_on(tcx: TyCtxt<'_>, owner: hir::OwnerId) -> ShallowLintLevelMap { - let store = unerased_lint_store(&tcx.sess); + let store = unerased_lint_store(tcx.sess); let attrs = tcx.hir_attrs(owner); let mut levels = LintLevelsBuilder { @@ -167,7 +167,7 @@ fn shallow_lint_levels_on(tcx: TyCtxt<'_>, owner: hir::OwnerId) -> ShallowLintLe }, warn_about_weird_lints: false, store, - registered_tools: &tcx.registered_tools(()), + registered_tools: tcx.registered_tools(()), }; if owner == hir::CRATE_OWNER_ID { @@ -605,7 +605,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { let orig_level = level; let lint_flag_val = Symbol::intern(lint_name); - let Ok(ids) = self.store.find_lints(&lint_name) else { + let Ok(ids) = self.store.find_lints(lint_name) else { // errors already handled above continue; }; @@ -629,7 +629,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { /// (e.g. if a forbid was already inserted on the same scope), then emits a /// diagnostic with no change to `specs`. fn insert_spec(&mut self, id: LintId, (mut level, src): LevelAndSource) { - let (old_level, old_src) = self.provider.get_lint_level(id.lint, &self.sess); + let (old_level, old_src) = self.provider.get_lint_level(id.lint, self.sess); if let Level::Expect(id) = &mut level && let LintExpectationId::Stable { .. } = id { @@ -929,12 +929,12 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { DeprecatedLintName { name, suggestion: sp, - replace: &new_lint_name, + replace: new_lint_name, }, ); let src = LintLevelSource::Node { - name: Symbol::intern(&new_lint_name), + name: Symbol::intern(new_lint_name), span: sp, reason, }; diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 829ac6903ded..c4d54c95e226 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -250,7 +250,7 @@ impl<'a> DecorateLint<'a, ()> for BuiltinUngatedAsyncFnTrackCaller<'_> { diag.span_label(self.label, fluent::lint_label); rustc_session::parse::add_feature_diagnostics( diag, - &self.parse_sess, + self.parse_sess, sym::async_fn_track_caller, ); diag diff --git a/compiler/rustc_lint/src/non_ascii_idents.rs b/compiler/rustc_lint/src/non_ascii_idents.rs index 62bb8c2c67d2..4f92fcd71c63 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -204,7 +204,7 @@ impl EarlyLintPass for NonAsciiIdents { // Get the skeleton as a `Symbol`. skeleton_buf.clear(); - skeleton_buf.extend(skeleton(&symbol_str)); + skeleton_buf.extend(skeleton(symbol_str)); let skeleton_sym = if *symbol_str == *skeleton_buf { symbol } else { diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 66dc726df892..d6ed0250efc7 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -334,7 +334,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name { Some(Ident::from_str(name)) } else { - attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name) + attr::find_by_name(cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name) .and_then(|attr| attr.meta()) .and_then(|meta| { meta.name_value_literal().and_then(|lit| { @@ -473,7 +473,7 @@ impl NonUpperCaseGlobals { fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) { let name = ident.name.as_str(); if name.chars().any(|c| c.is_lowercase()) { - let uc = NonSnakeCase::to_snake_case(&name).to_uppercase(); + let uc = NonSnakeCase::to_snake_case(name).to_uppercase(); // We cannot provide meaningful suggestions // if the characters are in the category of "Lowercase Letter". let sub = if *name != uc { @@ -520,7 +520,7 @@ impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals { fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) { // Lint for constants that look like binding identifiers (#7526) - if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind { + if let PatKind::Path(hir::QPath::Resolved(None, path)) = p.kind { if let Res::Def(DefKind::Const, _) = path.res { if path.segments.len() == 1 { NonUpperCaseGlobals::check_upper_case( diff --git a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs index c24846ca9398..44b23b8bdc0c 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -113,7 +113,7 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { for (assoc_pred, assoc_pred_span) in cx .tcx .explicit_item_bounds(proj.projection_ty.def_id) - .iter_instantiated_copied(cx.tcx, &proj.projection_ty.args) + .iter_instantiated_copied(cx.tcx, proj.projection_ty.args) { let assoc_pred = assoc_pred.fold_with(proj_replacer); let Ok(assoc_pred) = traits::fully_normalize( diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index cad2cd7fa4c8..fce750c9b558 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -28,7 +28,7 @@ impl<'tcx> LateLintPass<'tcx> for PassByValue { return; } } - if let Some(t) = path_for_pass_by_value(cx, &inner_ty) { + if let Some(t) = path_for_pass_by_value(cx, inner_ty) { cx.emit_spanned_lint( PASS_BY_VALUE, ty.span, diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 706c8c7add58..bae63ae17164 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -623,7 +623,7 @@ fn lint_nan<'tcx>( impl<'tcx> LateLintPass<'tcx> for TypeLimits { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) { match e.kind { - hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => { + hir::ExprKind::Unary(hir::UnOp::Neg, expr) => { // Propagate negation, if the negation itself isn't negated if self.negated_expr_id != Some(e.hir_id) { self.negated_expr_id = Some(expr.hir_id); @@ -632,14 +632,14 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits { } hir::ExprKind::Binary(binop, ref l, ref r) => { if is_comparison(binop) { - if !check_limits(cx, binop, &l, &r) { + if !check_limits(cx, binop, l, r) { cx.emit_spanned_lint(UNUSED_COMPARISONS, e.span, UnusedComparisons); } else { lint_nan(cx, e, binop, l, r); } } } - hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit), + hir::ExprKind::Lit(lit) => lint_literal(cx, self, e, lit), _ => {} }; @@ -685,7 +685,7 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits { ty::Int(int_ty) => { let (min, max) = int_ty_range(int_ty); let lit_val: i128 = match lit.kind { - hir::ExprKind::Lit(ref li) => match li.node { + hir::ExprKind::Lit(li) => match li.node { ast::LitKind::Int( v, ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed, @@ -699,7 +699,7 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits { ty::Uint(uint_ty) => { let (min, max): (u128, u128) = uint_ty_range(uint_ty); let lit_val: u128 = match lit.kind { - hir::ExprKind::Lit(ref li) => match li.node { + hir::ExprKind::Lit(li) => match li.node { ast::LitKind::Int(v, _) => v, _ => return true, }, @@ -1015,7 +1015,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { // We can't completely trust `repr(C)` markings, so make sure the fields are actually safe. let mut all_phantom = !variant.fields.is_empty(); for field in &variant.fields { - all_phantom &= match self.check_field_type_for_ffi(cache, &field, args) { + all_phantom &= match self.check_field_type_for_ffi(cache, field, args) { FfiSafe => false, // `()` fields are FFI-safe! FfiUnsafe { ty, .. } if ty.is_unit() => false, @@ -1399,7 +1399,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } } - if let hir::FnRetTy::Return(ref ret_hir) = decl.output { + if let hir::FnRetTy::Return(ret_hir) = decl.output { for (fn_ptr_ty, span) in self.find_fn_ptr_ty_with_external_abi(ret_hir, sig.output()) { self.check_type_for_ffi_and_report_errors(span, fn_ptr_ty, false, true); } @@ -1415,7 +1415,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { self.check_type_for_ffi_and_report_errors(input_hir.span, *input_ty, false, false); } - if let hir::FnRetTy::Return(ref ret_hir) = decl.output { + if let hir::FnRetTy::Return(ret_hir) = decl.output { self.check_type_for_ffi_and_report_errors(ret_hir.span, sig.output(), false, true); } } @@ -1487,13 +1487,13 @@ impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations { let abi = cx.tcx.hir().get_foreign_abi(it.hir_id()); match it.kind { - hir::ForeignItemKind::Fn(ref decl, _, _) if !vis.is_internal_abi(abi) => { + hir::ForeignItemKind::Fn(decl, _, _) if !vis.is_internal_abi(abi) => { vis.check_foreign_fn(it.owner_id.def_id, decl); } - hir::ForeignItemKind::Static(ref ty, _) if !vis.is_internal_abi(abi) => { + hir::ForeignItemKind::Static(ty, _) if !vis.is_internal_abi(abi) => { vis.check_foreign_static(it.owner_id, ty.span); } - hir::ForeignItemKind::Fn(ref decl, _, _) => vis.check_fn(it.owner_id.def_id, decl), + hir::ForeignItemKind::Fn(decl, _, _) => vis.check_fn(it.owner_id.def_id, decl), hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => (), } } @@ -1705,7 +1705,7 @@ impl InvalidAtomicOrdering { sym::AtomicI64, sym::AtomicI128, ]; - if let ExprKind::MethodCall(ref method_path, _, args, _) = &expr.kind + if let ExprKind::MethodCall(method_path, _, args, _) = &expr.kind && recognized_names.contains(&method_path.ident.name) && let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) && let Some(impl_did) = cx.tcx.impl_of_method(m_def_id) @@ -1766,7 +1766,7 @@ impl InvalidAtomicOrdering { } fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) { - if let ExprKind::Call(ref func, ref args) = expr.kind + if let ExprKind::Call(func, args) = expr.kind && let ExprKind::Path(ref func_qpath) = func.kind && let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id() && matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::fence | sym::compiler_fence)) diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 0ae91ac28a74..b4535c72d6c6 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -111,7 +111,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { } if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind - && let ty = cx.typeck_results().expr_ty(&await_expr) + && let ty = cx.typeck_results().expr_ty(await_expr) && let ty::Alias(ty::Opaque, ty::AliasTy { def_id: future_def_id, .. }) = ty.kind() && cx.tcx.ty_is_opaque_future(ty) && let async_fn_def_id = cx.tcx.parent(*future_def_id) @@ -132,9 +132,9 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { return; } - let ty = cx.typeck_results().expr_ty(&expr); + let ty = cx.typeck_results().expr_ty(expr); - let must_use_result = is_ty_must_use(cx, ty, &expr, expr.span); + let must_use_result = is_ty_must_use(cx, ty, expr, expr.span); let type_lint_emitted_or_suppressed = match must_use_result { Some(path) => { emit_must_use_untranslated(cx, &path, "", "", 1, false, expr_is_from_block); @@ -211,7 +211,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { expr_is_from_block: bool, ) -> bool { let maybe_def_id = match expr.kind { - hir::ExprKind::Call(ref callee, _) => { + hir::ExprKind::Call(callee, _) => { match callee.kind { hir::ExprKind::Path(ref qpath) => { match cx.qpath_res(qpath, callee.hir_id) { @@ -692,7 +692,7 @@ trait UnusedDelimLint { innermost = match &innermost.kind { ExprKind::AddrOf(_, _, expr) => expr, _ => { - if parser::contains_exterior_struct_lit(&innermost) { + if parser::contains_exterior_struct_lit(innermost) { return true; } else { break; @@ -721,7 +721,7 @@ trait UnusedDelimLint { return matches!(rhs.kind, ExprKind::Block(..)); } - _ => return parser::contains_exterior_struct_lit(&inner), + _ => return parser::contains_exterior_struct_lit(inner), } } } @@ -896,7 +896,7 @@ trait UnusedDelimLint { }; self.check_unused_delims_expr( cx, - &value, + value, ctx, followed_by_block, left_pos, @@ -919,7 +919,7 @@ trait UnusedDelimLint { StmtKind::Expr(ref expr) => { self.check_unused_delims_expr( cx, - &expr, + expr, UnusedDelimsCtx::BlockRetValue, false, None, diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 14bbe65d5f1f..169b56d40fae 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -427,7 +427,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { let crate_metadata = CrateMetadata::new( self.sess, - &self.cstore, + self.cstore, metadata, crate_root, raw_proc_macros, @@ -515,7 +515,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { Err(err) => { let missing_core = self.maybe_resolve_crate(sym::core, CrateDepKind::Explicit, None).is_err(); - err.report(&self.sess, span, missing_core); + err.report(self.sess, span, missing_core); None } } @@ -987,7 +987,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { self.report_unused_deps(krate); - info!("{:?}", CrateDump(&self.cstore)); + info!("{:?}", CrateDump(self.cstore)); } pub fn process_extern_crate( diff --git a/compiler/rustc_metadata/src/fs.rs b/compiler/rustc_metadata/src/fs.rs index 7eb2a347db21..4b451253f2b8 100644 --- a/compiler/rustc_metadata/src/fs.rs +++ b/compiler/rustc_metadata/src/fs.rs @@ -94,7 +94,7 @@ pub fn encode_and_write_metadata(tcx: TyCtxt<'_>) -> (EncodedMetadata, bool) { tcx.sess .parse_sess .span_diagnostic - .emit_artifact_notification(&out_filename.as_path(), "metadata"); + .emit_artifact_notification(out_filename.as_path(), "metadata"); } (filename, None) } else { diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 3a99ddc1b7af..2b5773320b4d 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -980,7 +980,7 @@ impl CrateError { for CrateMismatch { path, .. } in mismatches { sess.emit_err(errors::CrateLocationUnknownType { span, - path: &path, + path: path, crate_name, }); sess.emit_err(errors::LibFilenameForm { diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 909a977ccc9a..0250c92dd78b 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -394,7 +394,7 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) { native_library: |tcx, id| { tcx.native_libraries(id.krate) .iter() - .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib)) + .filter(|lib| native_libs::relevant_lib(tcx.sess, lib)) .find(|lib| { let Some(fm_id) = lib.foreign_module else { return false; diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 19c5e8e5d59e..d6964a241bfe 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -160,7 +160,7 @@ impl<'a, 'tcx> Encodable> for ExpnIndex { impl<'a, 'tcx> Encodable> for SyntaxContext { fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) { - rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s); + rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_ctxt, s); } } @@ -660,7 +660,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode // this as late as possible to give the prefetching as much time as possible to complete. let exported_symbols = stat!("exported-symbols", || { - self.encode_exported_symbols(&tcx.exported_symbols(LOCAL_CRATE)) + self.encode_exported_symbols(tcx.exported_symbols(LOCAL_CRATE)) }); // Encode the hygiene data. @@ -694,15 +694,15 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE), has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), - has_default_lib_allocator: attr::contains_name(&attrs, sym::default_lib_allocator), + has_default_lib_allocator: attr::contains_name(attrs, sym::default_lib_allocator), proc_macro_data, debugger_visualizers, - compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins), - needs_allocator: attr::contains_name(&attrs, sym::needs_allocator), - needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime), - no_builtins: attr::contains_name(&attrs, sym::no_builtins), - panic_runtime: attr::contains_name(&attrs, sym::panic_runtime), - profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime), + compiler_builtins: attr::contains_name(attrs, sym::compiler_builtins), + needs_allocator: attr::contains_name(attrs, sym::needs_allocator), + needs_panic_runtime: attr::contains_name(attrs, sym::needs_panic_runtime), + no_builtins: attr::contains_name(attrs, sym::no_builtins), + panic_runtime: attr::contains_name(attrs, sym::panic_runtime), + profiler_runtime: attr::contains_name(attrs, sym::profiler_runtime), symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(), crate_deps, @@ -1728,9 +1728,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_info_for_macro(&mut self, def_id: LocalDefId) { let tcx = self.tcx; - let hir::ItemKind::Macro(ref macro_def, _) = tcx.hir().expect_item(def_id).kind else { - bug!() - }; + let hir::ItemKind::Macro(macro_def, _) = tcx.hir().expect_item(def_id).kind else { bug!() }; self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules); record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body); } diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index 027994c40ab7..af076f3d4c7e 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -382,8 +382,8 @@ impl LazyArray { } fn from_bytes_impl(position: &[u8; 8], meta: &[u8; 8]) -> Option> { - let position = NonZeroUsize::new(u64::from_bytes(&position) as usize)?; - let len = u64::from_bytes(&meta) as usize; + let position = NonZeroUsize::new(u64::from_bytes(position) as usize)?; + let len = u64::from_bytes(meta) as usize; Some(LazyArray::from_position_and_num_elems(position, len)) } } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 58c0c6bab495..9d8168382d20 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -531,9 +531,7 @@ impl<'hir> Map<'hir> { pub fn get_module(self, module: LocalModDefId) -> (&'hir Mod<'hir>, Span, HirId) { let hir_id = HirId::make_owner(module.to_local_def_id()); match self.tcx.hir_owner(hir_id.owner).map(|o| o.node) { - Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => { - (m, span, hir_id) - } + Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(m), .. })) => (m, span, hir_id), Some(OwnerNode::Crate(item)) => (item, item.spans.inner_span, hir_id), node => panic!("not a module: {node:?}"), } @@ -1278,7 +1276,7 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String { ItemKind::ForeignMod { .. } => "foreign mod", ItemKind::GlobalAsm(..) => "global asm", ItemKind::TyAlias(..) => "ty", - ItemKind::OpaqueTy(ref opaque) => { + ItemKind::OpaqueTy(opaque) => { if opaque.in_trait { "opaque type in trait" } else { @@ -1314,10 +1312,10 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String { format!("{id} ({kind} `{}` in {})", ti.ident, path_str(ti.owner_id.def_id)) } - Some(Node::Variant(ref variant)) => { + Some(Node::Variant(variant)) => { format!("{id} (variant `{}` in {})", variant.ident, path_str(variant.def_id)) } - Some(Node::Field(ref field)) => { + Some(Node::Field(field)) => { format!("{id} (field `{}` in {})", field.ident, path_str(field.def_id)) } Some(Node::AnonConst(_)) => node_str("const"), @@ -1341,7 +1339,7 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String { ctor.ctor_def_id().map_or("".into(), |def_id| path_str(def_id)), ), Some(Node::Lifetime(_)) => node_str("lifetime"), - Some(Node::GenericParam(ref param)) => { + Some(Node::GenericParam(param)) => { format!("{id} (generic_param {})", path_str(param.def_id)) } Some(Node::Crate(..)) => String::from("(root_crate)"), diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index b76d1d6e141d..9d55295fb66b 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -178,7 +178,7 @@ impl Scope { }; let span = tcx.hir().span(hir_id); if let ScopeData::Remainder(first_statement_index) = self.data { - if let Node::Block(ref blk) = tcx.hir().get(hir_id) { + if let Node::Block(blk) = tcx.hir().get(hir_id) { // Want span for scope starting after the // indexed statement and ending at end of // `blk`; reuse span of `blk` and shift `lo` diff --git a/compiler/rustc_middle/src/mir/consts.rs b/compiler/rustc_middle/src/mir/consts.rs index a9d09709e842..84a9ab4013be 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -592,7 +592,7 @@ impl<'tcx> TyCtxt<'tcx> { let caller = self.sess.source_map().lookup_char_pos(topmost.lo()); self.const_caller_location( rustc_span::symbol::Symbol::intern( - &caller.file.name.for_codegen(&self.sess).to_string_lossy(), + &caller.file.name.for_codegen(self.sess).to_string_lossy(), ), caller.line as u32, caller.col_display as u32 + 1, diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 874c997c23be..d4778cdccf37 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -973,7 +973,7 @@ pub enum LocalInfo<'tcx> { impl<'tcx> LocalDecl<'tcx> { pub fn local_info(&self) -> &LocalInfo<'tcx> { - &self.local_info.as_ref().assert_crate_local() + self.local_info.as_ref().assert_crate_local() } /// Returns `true` only if local is a binding that can itself be diff --git a/compiler/rustc_middle/src/mir/spanview.rs b/compiler/rustc_middle/src/mir/spanview.rs index 38538a0b316a..46e5c74c73c9 100644 --- a/compiler/rustc_middle/src/mir/spanview.rs +++ b/compiler/rustc_middle/src/mir/spanview.rs @@ -369,7 +369,7 @@ where debug_indent, span, viewable.span ); from_pos = span.hi(); - make_html_snippet(tcx, span, Some(&viewable)) + make_html_snippet(tcx, span, Some(viewable)) } else { None }; @@ -439,7 +439,7 @@ where tcx, from_pos, to_pos, - &remaining_viewables, + remaining_viewables, subalt, layer + 1, w, @@ -472,7 +472,7 @@ where "{}After overlaps, writing (end span?) {:?} of viewable.span {:?}", debug_indent, span, viewable.span ); - if let Some(ref html_snippet) = make_html_snippet(tcx, span, Some(&viewable)) { + if let Some(ref html_snippet) = make_html_snippet(tcx, span, Some(viewable)) { from_pos = span.hi(); write_span(html_snippet, &viewable.tooltip, alt, layer, w)?; } diff --git a/compiler/rustc_middle/src/mir/statement.rs b/compiler/rustc_middle/src/mir/statement.rs index 3471d620ee69..be35a54be584 100644 --- a/compiler/rustc_middle/src/mir/statement.rs +++ b/compiler/rustc_middle/src/mir/statement.rs @@ -159,7 +159,7 @@ impl<'tcx> Place<'tcx> { #[inline] pub fn as_ref(&self) -> PlaceRef<'tcx> { - PlaceRef { local: self.local, projection: &self.projection } + PlaceRef { local: self.local, projection: self.projection } } /// Iterate over the projections in evaluation order, i.e., the first element is the base with diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index 6ab2da23a8ad..557c4d0f5642 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -40,7 +40,7 @@ impl<'tcx> PlaceTy<'tcx> { None => adt_def.non_enum_variant(), Some(variant_index) => { assert!(adt_def.is_enum()); - &adt_def.variant(variant_index) + adt_def.variant(variant_index) } }; let field_def = &variant_def.fields[f]; @@ -143,7 +143,7 @@ impl<'tcx> Place<'tcx> { where D: HasLocalDecls<'tcx>, { - Place::ty_from(self.local, &self.projection, local_decls, tcx) + Place::ty_from(self.local, self.projection, local_decls, tcx) } } @@ -152,7 +152,7 @@ impl<'tcx> PlaceRef<'tcx> { where D: HasLocalDecls<'tcx>, { - Place::ty_from(self.local, &self.projection, local_decls, tcx) + Place::ty_from(self.local, self.projection, local_decls, tcx) } } diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index 280f5d0a84ca..ee6567f6cc42 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -246,7 +246,7 @@ impl<'sess> OnDiskCache<'sess> { let index = SourceFileIndex(index as u32); let file_ptr: *const SourceFile = &**file as *const _; file_to_file_index.insert(file_ptr, index); - let source_file_id = EncodedSourceFileId::new(tcx, &file); + let source_file_id = EncodedSourceFileId::new(tcx, file); file_index_to_stable_id.insert(index, source_file_id); } @@ -482,13 +482,8 @@ pub struct CacheDecoder<'a, 'tcx> { impl<'a, 'tcx> CacheDecoder<'a, 'tcx> { #[inline] fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc { - let CacheDecoder { - tcx, - ref file_index_to_file, - ref file_index_to_stable_id, - ref source_map, - .. - } = *self; + let CacheDecoder { tcx, file_index_to_file, file_index_to_stable_id, source_map, .. } = + *self; file_index_to_file .borrow_mut() diff --git a/compiler/rustc_middle/src/thir/visit.rs b/compiler/rustc_middle/src/thir/visit.rs index 8feefb4c03cc..62c3ceeab8ab 100644 --- a/compiler/rustc_middle/src/thir/visit.rs +++ b/compiler/rustc_middle/src/thir/visit.rs @@ -226,7 +226,7 @@ pub fn walk_pat<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, pat: &Pat<' ty: _, is_primary: _, name: _, - } => visitor.visit_pat(&subpattern), + } => visitor.visit_pat(subpattern), Binding { .. } | Wild | Error(_) => {} Variant { subpatterns, adt_def: _, args: _, variant_index: _ } | Leaf { subpatterns } => { for subpattern in subpatterns { @@ -249,7 +249,7 @@ pub fn walk_pat<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, pat: &Pat<' } Or { pats } => { for pat in pats.iter() { - visitor.visit_pat(&pat); + visitor.visit_pat(pat); } } }; diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 6cd75e087276..c1bb03e99daa 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -686,7 +686,7 @@ impl<'tcx, N> ImplSource<'tcx, N> { pub fn borrow_nested_obligations(&self) -> &[N] { match self { ImplSource::UserDefined(i) => &i.nested, - ImplSource::Param(n) | ImplSource::Builtin(_, n) => &n, + ImplSource::Param(n) | ImplSource::Builtin(_, n) => n, } } diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index f50969dd967f..7650389415c2 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -99,7 +99,7 @@ pub struct AdtDefData { impl PartialOrd for AdtDefData { fn partial_cmp(&self, other: &AdtDefData) -> Option { - Some(self.cmp(&other)) + Some(self.cmp(other)) } } @@ -375,7 +375,7 @@ impl<'tcx> AdtDef<'tcx> { /// Asserts this is a struct or union and returns its unique variant. pub fn non_enum_variant(self) -> &'tcx VariantDef { assert!(self.is_struct() || self.is_union()); - &self.variant(FIRST_VARIANT) + self.variant(FIRST_VARIANT) } #[inline] diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 8b67e39667b8..81cf41889d49 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -297,7 +297,7 @@ impl<'tcx, D: TyDecoder>> Decodable for AllocId { impl<'tcx, D: TyDecoder>> Decodable for ty::SymbolName<'tcx> { fn decode(decoder: &mut D) -> Self { - ty::SymbolName::new(decoder.interner(), &decoder.read_str()) + ty::SymbolName::new(decoder.interner(), decoder.read_str()) } } diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index af5ffc20d489..c46ab9923592 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -183,11 +183,9 @@ impl<'tcx> Const<'tcx> { }; let lit_input = match expr.kind { - hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }), - hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind { - hir::ExprKind::Lit(ref lit) => { - Some(LitToConstInput { lit: &lit.node, ty, neg: true }) - } + hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }), + hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind { + hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: true }), _ => None, }, _ => None, diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index b26f98769c14..469593fe6634 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -235,7 +235,7 @@ impl<'tcx> Ty<'tcx> { _ => "fn item".into(), }, ty::FnPtr(_) => "fn pointer".into(), - ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => { + ty::Dynamic(inner, ..) if let Some(principal) = inner.principal() => { format!("`dyn {}`", tcx.def_path_str(principal.def_id())).into() } ty::Dynamic(..) => "trait object".into(), @@ -281,7 +281,7 @@ impl<'tcx> Ty<'tcx> { | ty::Float(_) | ty::Str | ty::Never => "type".into(), - ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(), + ty::Tuple(tys) if tys.is_empty() => "unit type".into(), ty::Adt(def, _) => def.descr().into(), ty::Foreign(_) => "extern type".into(), ty::Array(..) => "array".into(), diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 8fd08c724d2b..0c658fa1c80f 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -86,7 +86,7 @@ impl<'tcx> Ord for GenericArg<'tcx> { impl<'tcx> PartialOrd for GenericArg<'tcx> { fn partial_cmp(&self, other: &GenericArg<'tcx>) -> Option { - Some(self.cmp(&other)) + Some(self.cmp(other)) } } diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index 4a6e3cfacd3d..8316f9c30587 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -354,7 +354,7 @@ impl<'tcx> Generics { args: &'tcx [ty::GenericArg<'tcx>], ) -> &'tcx [ty::GenericArg<'tcx>] { let own = &args[self.parent_count..][..self.params.len()]; - if self.has_self && self.parent.is_none() { &own[1..] } else { &own } + if self.has_self && self.parent.is_none() { &own[1..] } else { own } } } diff --git a/compiler/rustc_middle/src/ty/impls_ty.rs b/compiler/rustc_middle/src/ty/impls_ty.rs index b03874a90e8d..59c0639fea21 100644 --- a/compiler/rustc_middle/src/ty/impls_ty.rs +++ b/compiler/rustc_middle/src/ty/impls_ty.rs @@ -29,7 +29,7 @@ where } let mut hasher = StableHasher::new(); - (&self[..]).hash_stable(hcx, &mut hasher); + self[..].hash_stable(hcx, &mut hasher); let hash: Fingerprint = hasher.finish(); cache.borrow_mut().insert(key, hash); diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index aca6acd783b9..4d8ac19dbe21 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -899,13 +899,13 @@ where ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8), // Tuples, coroutines and closures. - ty::Closure(_, ref args) => field_ty_or_layout( + ty::Closure(_, args) => field_ty_or_layout( TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this }, cx, i, ), - ty::Coroutine(def_id, ref args, _) => match this.variants { + ty::Coroutine(def_id, args, _) => match this.variants { Variants::Single { index } => TyMaybeWithLayout::Ty( args.as_coroutine() .state_tys(def_id, tcx) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2436daf62cf2..f240a99c8ffd 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1376,7 +1376,7 @@ impl<'tcx> InstantiatedPredicates<'tcx> { } pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter { - (&self).into_iter() + self.into_iter() } } @@ -2020,7 +2020,7 @@ impl<'tcx> TyCtxt<'tcx> { } for attr in self.get_attrs(did, sym::repr) { - for r in attr::parse_repr_attr(&self.sess, attr) { + for r in attr::parse_repr_attr(self.sess, attr) { flags.insert(match r { attr::ReprRust => ReprFlags::empty(), attr::ReprC => ReprFlags::IS_C, @@ -2286,7 +2286,7 @@ impl<'tcx> TyCtxt<'tcx> { where 'tcx: 'attr, { - let filter_fn = move |a: &&ast::Attribute| a.path_matches(&attr); + let filter_fn = move |a: &&ast::Attribute| a.path_matches(attr); if let Some(did) = did.as_local() { self.hir().attrs(self.hir().local_def_id_to_hir_id(did)).iter().filter(filter_fn) } else { @@ -2498,7 +2498,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option { let def_id = def_id.as_local()?; if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) { - if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind { + if let hir::ItemKind::OpaqueTy(opaque_ty) = item.kind { return match opaque_ty.origin { hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => { Some(parent) diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 6bbc8f70f515..64ae11df5b51 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -250,7 +250,7 @@ fn characteristic_def_id_of_type_cached<'a>( ty::Ref(_, ty, _) => characteristic_def_id_of_type_cached(ty, visited), - ty::Tuple(ref tys) => tys.iter().find_map(|ty| { + ty::Tuple(tys) => tys.iter().find_map(|ty| { if visited.insert(ty) { return characteristic_def_id_of_type_cached(ty, visited); } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index d478677c3679..a58362950ff9 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -322,7 +322,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id) { // If `Assoc` is unique, we don't want to talk about `Trait::Assoc`. - self.write_str(get_local_name(&self, *symbol, def_id, key).as_str())?; + self.write_str(get_local_name(self, *symbol, def_id, key).as_str())?; return Ok(true); } if let Some(symbol) = key.get_opt_name() { @@ -332,7 +332,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { && let Some(symbol) = parent_key.get_opt_name() { // Trait - self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?; + self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?; self.write_str("::")?; } else if let DefKind::Variant = kind && let Some(parent) = self.tcx().opt_parent(def_id) @@ -343,7 +343,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // For associated items and variants, we want the "full" path, namely, include // the parent type in the path. For example, `Iterator::Item`. - self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?; + self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?; self.write_str("::")?; } else if let DefKind::Struct | DefKind::Union @@ -358,7 +358,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // If not covered above, like for example items out of `impl` blocks, fallback. return Ok(false); } - self.write_str(get_local_name(&self, symbol, def_id, key).as_str())?; + self.write_str(get_local_name(self, symbol, def_id, key).as_str())?; return Ok(true); } Ok(false) @@ -660,7 +660,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { p!(print(ty::TypeAndMut { ty, mutbl })) } ty::Never => p!("!"), - ty::Tuple(ref tys) => { + ty::Tuple(tys) => { p!("(", comma_sep(tys.iter())); if tys.len() == 1 { p!(","); @@ -2399,7 +2399,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}"))); let mut available_names = possible_names - .filter(|name| !self.used_region_names.contains(&name)) + .filter(|name| !self.used_region_names.contains(name)) .collect::>(); debug!(?available_names); let num_available = available_names.len(); @@ -2445,7 +2445,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { br: ty::BoundRegion| { let (name, kind) = match br.kind { ty::BrAnon | ty::BrEnv => { - let name = next_name(&self); + let name = next_name(self); if let Some(lt_idx) = lifetime_idx { if lt_idx > binder_level_idx { @@ -2461,7 +2461,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { (name, ty::BrNamed(CRATE_DEF_ID.to_def_id(), name)) } ty::BrNamed(def_id, kw::UnderscoreLifetime | kw::Empty) => { - let name = next_name(&self); + let name = next_name(self); if let Some(lt_idx) = lifetime_idx { if lt_idx > binder_level_idx { diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 27e9be37fbff..d7d9afc30e7e 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -482,7 +482,7 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>( // the (anonymous) type of the same closure expression. So // all of their regions should be equated. let args = relate_args_invariantly(relation, a_args, b_args)?; - Ok(Ty::new_closure(tcx, a_id, &args)) + Ok(Ty::new_closure(tcx, a_id, args)) } (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index ea0e179c00de..ff333b3f09a3 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1590,7 +1590,7 @@ impl<'tcx> Deref for Region<'tcx> { #[inline] fn deref(&self) -> &RegionKind<'tcx> { - &self.0.0 + self.0.0 } } @@ -2114,7 +2114,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> { - if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(&ts))) } + if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) } } pub fn new_tup_from_iter(tcx: TyCtxt<'tcx>, iter: I) -> T::Output @@ -2270,7 +2270,7 @@ impl<'tcx> Ty<'tcx> { impl<'tcx> Ty<'tcx> { #[inline(always)] pub fn kind(self) -> &'tcx TyKind<'tcx> { - &self.0.0 + self.0.0 } #[inline(always)] @@ -2281,7 +2281,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn is_unit(self) -> bool { match self.kind() { - Tuple(ref tys) => tys.is_empty(), + Tuple(tys) => tys.is_empty(), _ => false, } } diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 914ff1fabd1b..0331546cdd90 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -241,7 +241,7 @@ impl<'tcx> TypeckResults<'tcx> { /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { match *qpath { - hir::QPath::Resolved(_, ref path) => path.res, + hir::QPath::Resolved(_, path) => path.res, hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self .type_dependent_def(id) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), diff --git a/compiler/rustc_mir_build/src/build/block.rs b/compiler/rustc_mir_build/src/build/block.rs index ab4cd24881f6..58295b397556 100644 --- a/compiler/rustc_mir_build/src/build/block.rs +++ b/compiler/rustc_mir_build/src/build/block.rs @@ -31,7 +31,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { destination, block, span, - &stmts, + stmts, expr, safety_mode, region_scope, @@ -42,7 +42,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { destination, block, span, - &stmts, + stmts, expr, safety_mode, region_scope, @@ -312,7 +312,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { None, Some((None, initializer_span)), ); - this.expr_into_pattern(block, &pattern, init) + this.expr_into_pattern(block, pattern, init) // irrefutable pattern }) }, diff --git a/compiler/rustc_mir_build/src/build/custom/mod.rs b/compiler/rustc_mir_build/src/build/custom/mod.rs index d302d538ad41..8c68a58d4062 100644 --- a/compiler/rustc_mir_build/src/build/custom/mod.rs +++ b/compiler/rustc_mir_build/src/build/custom/mod.rs @@ -88,7 +88,7 @@ pub(super) fn build_custom_mir<'tcx>( }; let res: PResult<_> = try { - pctxt.parse_args(¶ms)?; + pctxt.parse_args(params)?; pctxt.parse_body(expr)?; }; if let Err(err) = res { 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 7e9191a37d32..43e8348903ef 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -175,7 +175,7 @@ fn to_upvars_resolved_place_builder<'tcx>( projection: &[PlaceElem<'tcx>], ) -> Option> { let Some((capture_index, capture)) = - find_capture_matching_projections(&cx.upvars, var_hir_id, &projection) + find_capture_matching_projections(&cx.upvars, var_hir_id, projection) else { let closure_span = cx.tcx.def_span(closure_def_id); if !enable_precise_capture(closure_span) { @@ -683,7 +683,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, fake_borrow_deref_ty); let fake_borrow_temp = self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span)); - let projection = tcx.mk_place_elems(&base_place.projection); + let projection = tcx.mk_place_elems(base_place.projection); self.cfg.push_assign( block, source_info, diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 304870274ac6..83686667a4ae 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -212,7 +212,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let scrutinee_place = unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,)); - let mut arm_candidates = self.create_match_candidates(&scrutinee_place, &arms); + let mut arm_candidates = self.create_match_candidates(&scrutinee_place, arms); let match_has_guard = arm_candidates.iter().any(|(_, candidate)| candidate.has_guard); let mut candidates = @@ -424,7 +424,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.source_scope = source_scope; } - this.expr_into_dest(destination, arm_block, &&this.thir[arm.body]) + this.expr_into_dest(destination, arm_block, &this.thir[arm.body]) }) }) .collect(); @@ -505,7 +505,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let binding_end = self.bind_and_guard_matched_candidate( leaf_candidate, parent_bindings, - &fake_borrow_temps, + fake_borrow_temps, scrutinee_span, arm_match_scope, schedule_drops, @@ -613,7 +613,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { _ => { let place_builder = unpack!(block = self.lower_scrutinee(block, initializer, initializer.span)); - self.place_into_pattern(block, &irrefutable_pat, place_builder, true) + self.place_into_pattern(block, irrefutable_pat, place_builder, true) } } } @@ -625,7 +625,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { initializer: PlaceBuilder<'tcx>, set_match_place: bool, ) -> BlockAnd<()> { - let mut candidate = Candidate::new(initializer.clone(), &irrefutable_pat, false, self); + let mut candidate = Candidate::new(initializer.clone(), irrefutable_pat, false, self); let fake_borrow_temps = self.lower_match_tree( block, irrefutable_pat.span, @@ -700,7 +700,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { opt_match_place: Option<(Option<&Place<'tcx>>, Span)>, ) -> Option { self.visit_primary_bindings( - &pattern, + pattern, UserTypeProjections::none(), &mut |this, mutability, name, mode, var, span, ty, user_ty| { if visibility_scope.is_none() { @@ -1843,7 +1843,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let expr_span = expr.span; let expr_place_builder = unpack!(block = self.lower_scrutinee(block, expr, expr_span)); let wildcard = Pat::wildcard_from_ty(pat.ty); - let mut guard_candidate = Candidate::new(expr_place_builder.clone(), &pat, false, self); + let mut guard_candidate = Candidate::new(expr_place_builder.clone(), pat, false, self); let mut otherwise_candidate = Candidate::new(expr_place_builder.clone(), &wildcard, false, self); let fake_borrow_temps = self.lower_match_tree( diff --git a/compiler/rustc_mir_build/src/build/matches/simplify.rs b/compiler/rustc_mir_build/src/build/matches/simplify.rs index 6a40c8d840bd..8a6cb26242a1 100644 --- a/compiler/rustc_mir_build/src/build/matches/simplify.rs +++ b/compiler/rustc_mir_build/src/build/matches/simplify.rs @@ -69,7 +69,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { { existing_bindings.extend_from_slice(&new_bindings); mem::swap(&mut candidate.bindings, &mut existing_bindings); - candidate.subcandidates = self.create_or_subcandidates(candidate, &place, pats); + candidate.subcandidates = self.create_or_subcandidates(candidate, place, pats); return true; } diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index bdd4f2011ebe..6bd60972c8ba 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -736,7 +736,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // These are all binary tests. // // FIXME(#29623) we can be more clever here - let pattern_test = self.test(&match_pair); + let pattern_test = self.test(match_pair); if pattern_test.kind == test.kind { self.candidate_without_match_pair(match_pair_index, candidate); Some(0) diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 886d805454db..3d2396f33fc0 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -938,12 +938,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scope = self.declare_bindings( scope, expr.span, - &pat, + pat, None, Some((Some(&place), span)), ); let place_builder = PlaceBuilder::from(local); - unpack!(block = self.place_into_pattern(block, &pat, place_builder, false)); + unpack!(block = self.place_into_pattern(block, pat, place_builder, false)); } } self.source_scope = original_source_scope; @@ -954,7 +954,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.source_scope = source_scope; } - self.expr_into_dest(Place::return_place(), block, &expr) + self.expr_into_dest(Place::return_place(), block, expr) } fn set_correct_source_scope_for_arg( diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index b3d3863b5db7..d6ca873e9922 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -995,7 +995,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } if scope.region_scope == region_scope { - let region_scope_span = region_scope.span(self.tcx, &self.region_scope_tree); + let region_scope_span = region_scope.span(self.tcx, self.region_scope_tree); // Attribute scope exit drops to scope's closing brace. let scope_end = self.tcx.sess.source_map().end_point(region_scope_span); diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index fcb563607828..103b0d8e26a2 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -200,7 +200,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> { impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { fn thir(&self) -> &'a Thir<'tcx> { - &self.thir + self.thir } fn visit_block(&mut self, block: &Block) { diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index a46ad6423a03..527eadb277e1 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -51,7 +51,7 @@ impl<'tcx> Cx<'tcx> { let hir_id = stmt.hir_id; let opt_dxn_ext = self.region_scope_tree.opt_destruction_scope(hir_id.local_id); match stmt.kind { - hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => { + hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr) => { let stmt = Stmt { kind: StmtKind::Expr { scope: region::Scope { @@ -68,7 +68,7 @@ impl<'tcx> Cx<'tcx> { // ignore for purposes of the MIR None } - hir::StmtKind::Local(ref local) => { + hir::StmtKind::Local(local) => { let remainder_scope = region::Scope { id: block_id, data: region::ScopeData::Remainder(region::FirstStatementIndex::new( diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 50f57b28a983..6541b4f6a3e0 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -261,7 +261,7 @@ impl<'tcx> Cx<'tcx> { let kind = match expr.kind { // Here comes the interesting stuff: - hir::ExprKind::MethodCall(segment, receiver, ref args, fn_span) => { + hir::ExprKind::MethodCall(segment, receiver, args, fn_span) => { // Rewrite a.b(c) into UFCS form like Trait::b(a, c) let expr = self.method_callee(expr, segment.ident.span, None); info!("Using method span: {:?}", expr.span); @@ -278,7 +278,7 @@ impl<'tcx> Cx<'tcx> { } } - hir::ExprKind::Call(ref fun, ref args) => { + hir::ExprKind::Call(fun, ref args) => { if self.typeck_results().is_method_call(expr) { // The callee is something implementing Fn, FnMut, or FnOnce. // Find the actual method implementation being called and @@ -346,7 +346,7 @@ impl<'tcx> Cx<'tcx> { && let Some(adt_def) = expr_ty.ty_adt_def() { match qpath { - hir::QPath::Resolved(_, ref path) => match path.res { + hir::QPath::Resolved(_, path) => match path.res { Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => { Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id))) } @@ -407,21 +407,21 @@ impl<'tcx> Cx<'tcx> { } } - hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => { + hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, arg) => { ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: self.mirror_expr(arg) } } - hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => { + hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, arg) => { ExprKind::AddressOf { mutability, arg: self.mirror_expr(arg) } } - hir::ExprKind::Block(ref blk, _) => ExprKind::Block { block: self.mirror_block(blk) }, + hir::ExprKind::Block(blk, _) => ExprKind::Block { block: self.mirror_block(blk) }, - hir::ExprKind::Assign(ref lhs, ref rhs, _) => { + hir::ExprKind::Assign(lhs, rhs, _) => { ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) } } - hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => { + hir::ExprKind::AssignOp(op, lhs, rhs) => { if self.typeck_results().is_method_call(expr) { let lhs = self.mirror_expr(lhs); let rhs = self.mirror_expr(rhs); @@ -435,9 +435,9 @@ impl<'tcx> Cx<'tcx> { } } - hir::ExprKind::Lit(ref lit) => ExprKind::Literal { lit, neg: false }, + hir::ExprKind::Lit(lit) => ExprKind::Literal { lit, neg: false }, - hir::ExprKind::Binary(op, ref lhs, ref rhs) => { + hir::ExprKind::Binary(op, lhs, rhs) => { if self.typeck_results().is_method_call(expr) { let lhs = self.mirror_expr(lhs); let rhs = self.mirror_expr(rhs); @@ -466,7 +466,7 @@ impl<'tcx> Cx<'tcx> { } } - hir::ExprKind::Index(ref lhs, ref index, brackets_span) => { + hir::ExprKind::Index(lhs, index, brackets_span) => { if self.typeck_results().is_method_call(expr) { let lhs = self.mirror_expr(lhs); let index = self.mirror_expr(index); @@ -482,7 +482,7 @@ impl<'tcx> Cx<'tcx> { } } - hir::ExprKind::Unary(hir::UnOp::Deref, ref arg) => { + hir::ExprKind::Unary(hir::UnOp::Deref, arg) => { if self.typeck_results().is_method_call(expr) { let arg = self.mirror_expr(arg); self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span) @@ -491,7 +491,7 @@ impl<'tcx> Cx<'tcx> { } } - hir::ExprKind::Unary(hir::UnOp::Not, ref arg) => { + hir::ExprKind::Unary(hir::UnOp::Not, arg) => { if self.typeck_results().is_method_call(expr) { let arg = self.mirror_expr(arg); self.overloaded_operator(expr, Box::new([arg])) @@ -500,18 +500,18 @@ impl<'tcx> Cx<'tcx> { } } - hir::ExprKind::Unary(hir::UnOp::Neg, ref arg) => { + hir::ExprKind::Unary(hir::UnOp::Neg, arg) => { if self.typeck_results().is_method_call(expr) { let arg = self.mirror_expr(arg); self.overloaded_operator(expr, Box::new([arg])) - } else if let hir::ExprKind::Lit(ref lit) = arg.kind { + } else if let hir::ExprKind::Lit(lit) = arg.kind { ExprKind::Literal { lit, neg: true } } else { ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) } } } - hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() { + hir::ExprKind::Struct(qpath, fields, ref base) => match expr_ty.kind() { ty::Adt(adt, args) => match adt.adt_kind() { AdtKind::Struct | AdtKind::Union => { let user_provided_types = self.typeck_results().user_provided_types(); @@ -614,13 +614,13 @@ impl<'tcx> Cx<'tcx> { self.convert_path_expr(expr, res) } - hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm(Box::new(InlineAsmExpr { + hir::ExprKind::InlineAsm(asm) => ExprKind::InlineAsm(Box::new(InlineAsmExpr { template: asm.template, operands: asm .operands .iter() .map(|(op, _op_sp)| match *op { - hir::InlineAsmOperand::In { reg, ref expr } => { + hir::InlineAsmOperand::In { reg, expr } => { InlineAsmOperand::In { reg, expr: self.mirror_expr(expr) } } hir::InlineAsmOperand::Out { reg, late, ref expr } => { @@ -630,20 +630,17 @@ impl<'tcx> Cx<'tcx> { expr: expr.map(|expr| self.mirror_expr(expr)), } } - hir::InlineAsmOperand::InOut { reg, late, ref expr } => { + hir::InlineAsmOperand::InOut { reg, late, expr } => { InlineAsmOperand::InOut { reg, late, expr: self.mirror_expr(expr) } } - hir::InlineAsmOperand::SplitInOut { - reg, - late, - ref in_expr, - ref out_expr, - } => InlineAsmOperand::SplitInOut { - reg, - late, - in_expr: self.mirror_expr(in_expr), - out_expr: out_expr.map(|expr| self.mirror_expr(expr)), - }, + hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, ref out_expr } => { + InlineAsmOperand::SplitInOut { + reg, + late, + in_expr: self.mirror_expr(in_expr), + out_expr: out_expr.map(|expr| self.mirror_expr(expr)), + } + } hir::InlineAsmOperand::Const { ref anon_const } => { let value = mir::Const::from_anon_const(tcx, anon_const.def_id, self.param_env); @@ -686,7 +683,7 @@ impl<'tcx> Cx<'tcx> { ExprKind::ConstBlock { did, args } } // Now comes the rote stuff: - hir::ExprKind::Repeat(ref v, _) => { + hir::ExprKind::Repeat(v, _) => { let ty = self.typeck_results().expr_ty(expr); let ty::Array(_, count) = ty.kind() else { span_bug!(expr.span, "unexpected repeat expr ty: {:?}", ty); @@ -722,12 +719,12 @@ impl<'tcx> Cx<'tcx> { then: self.mirror_expr(then), else_opt: else_opt.map(|el| self.mirror_expr(el)), }, - hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match { + hir::ExprKind::Match(discr, arms, _) => ExprKind::Match { scrutinee: self.mirror_expr(discr), scrutinee_hir_id: discr.hir_id, arms: arms.iter().map(|a| self.convert_arm(a)).collect(), }, - hir::ExprKind::Loop(ref body, ..) => { + hir::ExprKind::Loop(body, ..) => { let block_ty = self.typeck_results().node_type(body.hir_id); let temp_lifetime = self .rvalue_scopes @@ -741,12 +738,12 @@ impl<'tcx> Cx<'tcx> { }); ExprKind::Loop { body } } - hir::ExprKind::Field(ref source, ..) => ExprKind::Field { + hir::ExprKind::Field(source, ..) => ExprKind::Field { lhs: self.mirror_expr(source), variant_index: FIRST_VARIANT, name: self.typeck_results.field_index(expr.hir_id), }, - hir::ExprKind::Cast(ref source, ref cast_ty) => { + hir::ExprKind::Cast(source, cast_ty) => { // Check for a user-given type annotation on this `cast` let user_provided_types = self.typeck_results.user_provided_types(); let user_ty = user_provided_types.get(cast_ty.hir_id); @@ -756,7 +753,7 @@ impl<'tcx> Cx<'tcx> { expr, cast_ty.hir_id, user_ty, ); - let cast = self.mirror_expr_cast(*source, temp_lifetime, expr.span); + let cast = self.mirror_expr_cast(source, temp_lifetime, expr.span); if let Some(user_ty) = user_ty { // NOTE: Creating a new Expr and wrapping a Cast inside of it may be @@ -777,7 +774,7 @@ impl<'tcx> Cx<'tcx> { cast } } - hir::ExprKind::Type(ref source, ref ty) => { + hir::ExprKind::Type(source, ty) => { let user_provided_types = self.typeck_results.user_provided_types(); let user_ty = user_provided_types.get(ty.hir_id).copied().map(Box::new); debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty); @@ -788,15 +785,11 @@ impl<'tcx> Cx<'tcx> { ExprKind::ValueTypeAscription { source: mirrored, user_ty } } } - hir::ExprKind::DropTemps(ref source) => { - ExprKind::Use { source: self.mirror_expr(source) } - } - hir::ExprKind::Array(ref fields) => { - ExprKind::Array { fields: self.mirror_exprs(fields) } - } - hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) }, + hir::ExprKind::DropTemps(source) => ExprKind::Use { source: self.mirror_expr(source) }, + hir::ExprKind::Array(fields) => ExprKind::Array { fields: self.mirror_exprs(fields) }, + hir::ExprKind::Tup(fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) }, - hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: self.mirror_expr(v) }, + hir::ExprKind::Yield(v, _) => ExprKind::Yield { value: self.mirror_expr(v) }, hir::ExprKind::Err(_) => unreachable!(), }; @@ -870,10 +863,10 @@ impl<'tcx> Cx<'tcx> { fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId { let arm = Arm { - pattern: self.pattern_from_hir(&arm.pat), + pattern: self.pattern_from_hir(arm.pat), guard: arm.guard.as_ref().map(|g| match g { - hir::Guard::If(ref e) => Guard::If(self.mirror_expr(e)), - hir::Guard::IfLet(ref l) => { + hir::Guard::If(e) => Guard::If(self.mirror_expr(e)), + hir::Guard::IfLet(l) => { Guard::IfLet(self.pattern_from_hir(l.pat), self.mirror_expr(l.init)) } }), diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 261bd30b94ac..0427f66db287 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -27,10 +27,10 @@ pub(crate) fn thir_body( if let Some(reported) = cx.typeck_results.tainted_by_errors { return Err(reported); } - let expr = cx.mirror_expr(&body.value); + let expr = cx.mirror_expr(body.value); let owner_id = hir.local_def_id_to_hir_id(owner_def); - if let Some(ref fn_decl) = hir.fn_decl_by_hir_id(owner_id) { + if let Some(fn_decl) = hir.fn_decl_by_hir_id(owner_id) { let closure_env_param = cx.closure_env_param(owner_def, owner_id); let explicit_params = cx.explicit_params(owner_id, fn_decl, body); cx.thir.params = closure_env_param.into_iter().chain(explicit_params).collect(); 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 8c3d09c19a15..4cc3bbfcf43b 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -298,7 +298,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { tcx: self.tcx, param_env: self.param_env, module: self.tcx.parent_module(self.lint_level).to_def_id(), - pattern_arena: &self.pattern_arena, + pattern_arena: self.pattern_arena, match_span, refutable, } 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 0c7c2c6f9b4b..479f6c0a3ca4 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs @@ -74,7 +74,7 @@ fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> { fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) { if let PatKind::Or { pats } = &pat.kind { for pat in pats.iter() { - expand(&pat, vec); + expand(pat, vec); } } else { vec.push(pat) @@ -1099,7 +1099,7 @@ impl ConstructorSet { for variant in visible_variants { let ctor = Variant(*variant); - if seen_set.contains(&variant) { + if seen_set.contains(variant) { present.push(ctor); } else { missing.push(ctor); @@ -1108,7 +1108,7 @@ impl ConstructorSet { for variant in hidden_variants { let ctor = Variant(*variant); - if seen_set.contains(&variant) { + if seen_set.contains(variant) { present.push(ctor); } else { skipped_a_hidden_variant = true; diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 0811ab6a0a6b..d80497fd45f9 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -266,16 +266,16 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { return self.lower_path(qpath, pat.hir_id, pat.span); } - hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => { + hir::PatKind::Ref(subpattern, _) | hir::PatKind::Box(subpattern) => { PatKind::Deref { subpattern: self.lower_pattern(subpattern) } } - hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => { + hir::PatKind::Slice(prefix, ref slice, suffix) => { self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix) } - hir::PatKind::Tuple(ref pats, ddpos) => { - let ty::Tuple(ref tys) = ty.kind() else { + hir::PatKind::Tuple(pats, ddpos) => { + let ty::Tuple(tys) = ty.kind() else { span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty); }; let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos); @@ -325,7 +325,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } } - hir::PatKind::TupleStruct(ref qpath, ref pats, ddpos) => { + hir::PatKind::TupleStruct(ref qpath, pats, ddpos) => { let res = self.typeck_results.qpath_res(qpath, pat.hir_id); let ty::Adt(adt_def, _) = ty.kind() else { span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty); @@ -335,20 +335,20 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns) } - hir::PatKind::Struct(ref qpath, ref fields, _) => { + hir::PatKind::Struct(ref qpath, fields, _) => { let res = self.typeck_results.qpath_res(qpath, pat.hir_id); let subpatterns = fields .iter() .map(|field| FieldPat { field: self.typeck_results.field_index(field.hir_id), - pattern: self.lower_pattern(&field.pat), + pattern: self.lower_pattern(field.pat), }) .collect(); self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns) } - hir::PatKind::Or(ref pats) => PatKind::Or { pats: self.lower_patterns(pats) }, + hir::PatKind::Or(pats) => PatKind::Or { pats: self.lower_patterns(pats) }, }; Box::new(Pat { span, ty, kind }) diff --git a/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs b/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs index da7b6587a722..461c44a169c8 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs @@ -648,7 +648,7 @@ impl<'tcx> Usefulness<'tcx> { } else { witnesses .into_iter() - .map(|witness| witness.apply_constructor(pcx, &ctor)) + .map(|witness| witness.apply_constructor(pcx, ctor)) .collect() }; WithWitnesses(new_witnesses) @@ -934,7 +934,7 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> { let relevant_patterns = self.patterns.iter().filter(|pat| ctor.is_covered_by(pcx, pat.ctor())); for pat in relevant_patterns { - let specialized = pat.specialize(pcx, &ctor); + let specialized = pat.specialize(pcx, ctor); for (subpat, column) in specialized.iter().zip(&mut specialized_columns) { if subpat.is_or_pat() { column.patterns.extend(subpat.flatten_or_pat()) diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index 25ba67a63ece..958fa0d17cd3 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -481,12 +481,8 @@ where ) -> (BasicBlock, Unwind) { let (succ, unwind) = self.drop_ladder_bottom(); if !adt.is_enum() { - let fields = self.move_paths_for_fields( - self.place, - self.path, - &adt.variant(FIRST_VARIANT), - args, - ); + let fields = + self.move_paths_for_fields(self.place, self.path, adt.variant(FIRST_VARIANT), args); self.drop_ladder(fields, succ, unwind) } else { self.open_drop_for_multivariant(adt, args, succ, unwind) @@ -518,7 +514,7 @@ where self.place, ProjectionElem::Downcast(Some(variant.name), variant_index), ); - let fields = self.move_paths_for_fields(base_place, variant_path, &variant, args); + let fields = self.move_paths_for_fields(base_place, variant_path, variant, args); values.push(discr.val); if let Unwind::To(unwind) = unwind { // We can't use the half-ladder from the original @@ -859,14 +855,14 @@ where fn open_drop(&mut self) -> BasicBlock { let ty = self.place_ty(self.place); match ty.kind() { - ty::Closure(_, args) => self.open_drop_for_tuple(&args.as_closure().upvar_tys()), + ty::Closure(_, args) => self.open_drop_for_tuple(args.as_closure().upvar_tys()), // Note that `elaborate_drops` only drops the upvars of a coroutine, // and this is ok because `open_drop` here can only be reached // within that own coroutine's resume function. // This should only happen for the self argument on the resume function. // It effectively only contains upvars until the coroutine transformation runs. // See librustc_body/transform/coroutine.rs for more details. - ty::Coroutine(_, args, _) => self.open_drop_for_tuple(&args.as_coroutine().upvar_tys()), + ty::Coroutine(_, args, _) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()), ty::Tuple(fields) => self.open_drop_for_tuple(fields), ty::Adt(def, args) => self.open_drop_for_adt(*def, args), ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind), diff --git a/compiler/rustc_mir_dataflow/src/framework/direction.rs b/compiler/rustc_mir_dataflow/src/framework/direction.rs index 70451edd5004..04c9f7a016cc 100644 --- a/compiler/rustc_mir_dataflow/src/framework/direction.rs +++ b/compiler/rustc_mir_dataflow/src/framework/direction.rs @@ -196,7 +196,7 @@ impl Direction for Backward { { results.reset_to_block_entry(state, block); - vis.visit_block_end(results, &state, block_data, block); + vis.visit_block_end(results, state, block_data, block); // Terminator let loc = Location { block, statement_index: block_data.statements.len() }; diff --git a/compiler/rustc_mir_dataflow/src/framework/engine.rs b/compiler/rustc_mir_dataflow/src/framework/engine.rs index a29962d7717a..204e854235fd 100644 --- a/compiler/rustc_mir_dataflow/src/framework/engine.rs +++ b/compiler/rustc_mir_dataflow/src/framework/engine.rs @@ -295,7 +295,7 @@ where let mut results = Results { analysis, entry_sets, _marker: PhantomData }; if tcx.sess.opts.unstable_opts.dump_mir_dataflow { - let res = write_graphviz_results(tcx, &body, &mut results, pass_name); + let res = write_graphviz_results(tcx, body, &mut results, pass_name); if let Err(e) = res { error!("Failed to write graphviz dataflow results: {}", e); } diff --git a/compiler/rustc_mir_dataflow/src/framework/lattice.rs b/compiler/rustc_mir_dataflow/src/framework/lattice.rs index 3b89598d2899..1c2b475a43c9 100644 --- a/compiler/rustc_mir_dataflow/src/framework/lattice.rs +++ b/compiler/rustc_mir_dataflow/src/framework/lattice.rs @@ -342,7 +342,7 @@ impl Clone for MaybeReachable { fn clone_from(&mut self, source: &Self) { match (&mut *self, source) { (MaybeReachable::Reachable(x), MaybeReachable::Reachable(y)) => { - x.clone_from(&y); + x.clone_from(y); } _ => *self = source.clone(), } diff --git a/compiler/rustc_mir_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index c968e7aea8fd..61be100d70e9 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -409,7 +409,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeInitializedPlaces<'_, 'tcx> { } let enum_ = discr.place().and_then(|discr| { - switch_on_enum_discriminant(self.tcx, &self.body, &self.body[block], discr) + switch_on_enum_discriminant(self.tcx, self.body, &self.body[block], discr) }); let Some((enum_place, enum_def)) = enum_ else { @@ -540,7 +540,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeUninitializedPlaces<'_, 'tcx> { } let enum_ = discr.place().and_then(|discr| { - switch_on_enum_discriminant(self.tcx, &self.body, &self.body[block], discr) + switch_on_enum_discriminant(self.tcx, self.body, &self.body[block], discr) }); let Some((enum_place, enum_def)) = enum_ else { diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index d3dce641ba1f..f9468c8e8ccb 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -34,7 +34,7 @@ impl<'tcx> MirPass<'tcx> for SanityCheck { } let param_env = tcx.param_env(def_id); - let move_data = MoveData::gather_moves(&body, tcx, param_env, |_| true); + let move_data = MoveData::gather_moves(body, tcx, param_env, |_| true); let mdpe = MoveDataParamEnv { move_data, param_env }; if has_rustc_mir_with(tcx, def_id, sym::rustc_peek_maybe_init).is_some() { diff --git a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs index 61bf530f11c1..3195cd3622dc 100644 --- a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs +++ b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs @@ -13,7 +13,7 @@ pub struct CheckConstItemMutation; impl<'tcx> MirLint<'tcx> for CheckConstItemMutation { fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) { let mut checker = ConstMutationChecker { body, tcx, target_local: None }; - checker.visit_body(&body); + checker.visit_body(body); } } @@ -98,7 +98,7 @@ impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> { if !lhs.projection.is_empty() { if let Some(def_id) = self.is_const_item_without_destructor(lhs.local) && let Some((lint_root, span, item)) = - self.should_lint_const_item_usage(&lhs, def_id, loc) + self.should_lint_const_item_usage(lhs, def_id, loc) { self.tcx.emit_spanned_lint( CONST_ITEM_MUTATION, @@ -132,12 +132,7 @@ impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> { // the `self` parameter of a method call (as the terminator of our current // BasicBlock). If so, we emit a more specific lint. let method_did = self.target_local.and_then(|target_local| { - rustc_middle::util::find_self_call( - self.tcx, - &self.body, - target_local, - loc.block, - ) + rustc_middle::util::find_self_call(self.tcx, self.body, target_local, loc.block) }); let lint_loc = if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc }; diff --git a/compiler/rustc_mir_transform/src/check_packed_ref.rs b/compiler/rustc_mir_transform/src/check_packed_ref.rs index 9ee0a7040716..77bcba50a3cd 100644 --- a/compiler/rustc_mir_transform/src/check_packed_ref.rs +++ b/compiler/rustc_mir_transform/src/check_packed_ref.rs @@ -12,7 +12,7 @@ impl<'tcx> MirLint<'tcx> for CheckPackedRef { let param_env = tcx.param_env(body.source.def_id()); let source_info = SourceInfo::outermost(body.span); let mut checker = PackedRefChecker { body, tcx, param_env, source_info }; - checker.visit_body(&body); + checker.visit_body(body); } } diff --git a/compiler/rustc_mir_transform/src/check_unsafety.rs b/compiler/rustc_mir_transform/src/check_unsafety.rs index 8872f9a97d74..cfcd5acb9e95 100644 --- a/compiler/rustc_mir_transform/src/check_unsafety.rs +++ b/compiler/rustc_mir_transform/src/check_unsafety.rs @@ -494,7 +494,7 @@ fn unsafety_check_result(tcx: TyCtxt<'_>, def: LocalDefId) -> &UnsafetyCheckResu let param_env = tcx.param_env(def); let mut checker = UnsafetyChecker::new(body, def, tcx, param_env); - checker.visit_body(&body); + checker.visit_body(body); let unused_unsafes = (!tcx.is_typeck_child(def.to_def_id())) .then(|| check_unused_unsafe(tcx, def, &checker.used_unsafe_blocks)); diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index 0adbb078105a..42d33f4f5179 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -606,7 +606,7 @@ impl CanConstProp { for arg in body.args_iter() { cpv.found_assignment.insert(arg); } - cpv.visit_body(&body); + cpv.visit_body(body); cpv.can_const_prop } } diff --git a/compiler/rustc_mir_transform/src/const_prop_lint.rs b/compiler/rustc_mir_transform/src/const_prop_lint.rs index a23ba9c4aa9f..da315bb86ac6 100644 --- a/compiler/rustc_mir_transform/src/const_prop_lint.rs +++ b/compiler/rustc_mir_transform/src/const_prop_lint.rs @@ -453,7 +453,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { cond: &Operand<'tcx>, location: Location, ) -> Option { - let value = &self.eval_operand(&cond, location)?; + let value = &self.eval_operand(cond, location)?; trace!("assertion on {:?} should be {:?}", value, expected); let expected = Scalar::from_bool(expected); @@ -626,7 +626,7 @@ impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> { self.check_assertion(*expected, msg, cond, location); } TerminatorKind::SwitchInt { ref discr, ref targets } => { - if let Some(ref value) = self.eval_operand(&discr, location) + if let Some(ref value) = self.eval_operand(discr, location) && let Some(value_const) = self.use_ecx(location, |this| this.ecx.read_scalar(value)) && let Ok(constant) = value_const.try_to_int() diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index f5db7ce97eba..74009496e75d 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -50,7 +50,7 @@ fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { Replacer { tcx, - copy_classes: &ssa.copy_classes(), + copy_classes: ssa.copy_classes(), fully_moved, borrowed_locals, storage_to_remove, @@ -124,7 +124,7 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> { } fn visit_place(&mut self, place: &mut Place<'tcx>, ctxt: PlaceContext, loc: Location) { - if let Some(new_projection) = self.process_projection(&place.projection, loc) { + if let Some(new_projection) = self.process_projection(place.projection, loc) { place.projection = self.tcx().mk_place_elems(&new_projection); } diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs index dfafd8598306..aa4d8ddad566 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -651,7 +651,7 @@ fn locals_live_across_suspend_points<'tcx>( always_live_locals: &BitSet, movable: bool, ) -> LivenessInfo { - let body_ref: &Body<'_> = &body; + let body_ref: &Body<'_> = body; // Calculate when MIR locals have live storage. This gives us an upper bound of their // lifetimes. @@ -742,7 +742,7 @@ fn locals_live_across_suspend_points<'tcx>( // saving. let live_locals_at_suspension_points = live_locals_at_suspension_points .iter() - .map(|live_here| saved_locals.renumber_bitset(&live_here)) + .map(|live_here| saved_locals.renumber_bitset(live_here)) .collect(); let storage_conflicts = compute_storage_conflicts( @@ -778,7 +778,7 @@ impl CoroutineSavedLocals { /// Transforms a `BitSet` that contains only locals saved across yield points to the /// equivalent `BitSet`. fn renumber_bitset(&self, input: &BitSet) -> BitSet { - assert!(self.superset(&input), "{:?} not a superset of {:?}", self.0, input); + assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input); let mut out = BitSet::new_empty(self.count()); for (saved_local, local) in self.iter_enumerated() { if input.contains(local) { @@ -829,7 +829,7 @@ fn compute_storage_conflicts<'mir, 'tcx>( // Compute the storage conflicts for all eligible locals. let mut visitor = StorageConflictVisitor { body, - saved_locals: &saved_locals, + saved_locals: saved_locals, local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()), }; @@ -1128,7 +1128,7 @@ fn create_coroutine_drop_shim<'tcx>( // The returned state and the poisoned state fall through to the default // case which is just to return - insert_switch(&mut body, cases, &transform, TerminatorKind::Return); + insert_switch(&mut body, cases, transform, TerminatorKind::Return); for block in body.basic_blocks_mut() { let kind = &mut block.terminator_mut().kind; @@ -1465,7 +1465,7 @@ pub(crate) fn mir_coroutine_witnesses<'tcx>( // The witness simply contains all locals live across suspend points. - let always_live_locals = always_storage_live_locals(&body); + let always_live_locals = always_storage_live_locals(body); let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable); // Extract locals which are live across suspension point into `layout` @@ -1473,7 +1473,7 @@ pub(crate) fn mir_coroutine_witnesses<'tcx>( // `storage_liveness` tells us which locals have live storage at suspension points let (_, coroutine_layout, _) = compute_layout(liveness_info, body); - check_suspend_tys(tcx, &coroutine_layout, &body); + check_suspend_tys(tcx, &coroutine_layout, body); Some(coroutine_layout) } @@ -1564,7 +1564,7 @@ impl<'tcx> MirPass<'tcx> for StateTransform { }, ); - let always_live_locals = always_storage_live_locals(&body); + let always_live_locals = always_storage_live_locals(body); let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable); diff --git a/compiler/rustc_mir_transform/src/coverage/counters.rs b/compiler/rustc_mir_transform/src/coverage/counters.rs index 1bc3c25c653b..1e11d8d09b60 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters.rs @@ -222,7 +222,7 @@ impl<'a> MakeBcbCounters<'a> { // all `BasicCoverageBlock` nodes in the loop are visited before visiting any node outside // the loop. The `traversal` state includes a `context_stack`, providing a way to know if // the current BCB is in one or more nested loops or not. - let mut traversal = TraverseCoverageGraphWithLoops::new(&self.basic_coverage_blocks); + let mut traversal = TraverseCoverageGraphWithLoops::new(self.basic_coverage_blocks); while let Some(bcb) = traversal.next() { if bcb_has_coverage_spans(bcb) { debug!("{:?} has at least one coverage span. Get or make its counter", bcb); @@ -425,7 +425,7 @@ impl<'a> MakeBcbCounters<'a> { traversal: &TraverseCoverageGraphWithLoops<'_>, branches: &[BcbBranch], ) -> BcbBranch { - let good_reloop_branch = self.find_good_reloop_branch(traversal, &branches); + let good_reloop_branch = self.find_good_reloop_branch(traversal, branches); if let Some(reloop_branch) = good_reloop_branch { assert!(self.branch_has_no_counter(&reloop_branch)); debug!("Selecting reloop branch {reloop_branch:?} to get an expression"); @@ -508,7 +508,7 @@ impl<'a> MakeBcbCounters<'a> { fn bcb_branches(&self, from_bcb: BasicCoverageBlock) -> Vec { self.bcb_successors(from_bcb) .iter() - .map(|&to_bcb| BcbBranch::from_to(from_bcb, to_bcb, &self.basic_coverage_blocks)) + .map(|&to_bcb| BcbBranch::from_to(from_bcb, to_bcb, self.basic_coverage_blocks)) .collect::>() } diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 6bab62aa8540..7defc9ec148a 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -38,7 +38,7 @@ impl CoverageGraph { } let bcb_data = &bcbs[bcb]; let mut bcb_successors = Vec::new(); - for successor in bcb_filtered_successors(&mir_body, bcb_data.last_bb()) + for successor in bcb_filtered_successors(mir_body, bcb_data.last_bb()) .filter_map(|successor_bb| bb_to_bcb[successor_bb]) { if !seen[successor] { diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 97e4468a0e8b..796150f93158 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -142,7 +142,7 @@ impl<'a, 'tcx> Instrumentor<'a, 'tcx> { //////////////////////////////////////////////////// // Compute coverage spans from the `CoverageGraph`. let coverage_spans = CoverageSpans::generate_coverage_spans( - &self.mir_body, + self.mir_body, fn_sig_span, body_span, &self.basic_coverage_blocks, @@ -240,7 +240,7 @@ impl<'a, 'tcx> Instrumentor<'a, 'tcx> { ); // Inject a counter into the newly-created BB. - inject_statement(self.mir_body, self.make_mir_coverage_kind(&counter_kind), new_bb); + inject_statement(self.mir_body, self.make_mir_coverage_kind(counter_kind), new_bb); } mappings diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index bf5722b3d00b..dcc960e1e020 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -20,7 +20,7 @@ impl<'tcx> MirPass<'tcx> for CtfeLimit { .filter_map(|(node, node_data)| { if matches!(node_data.terminator().kind, TerminatorKind::Call { .. }) // Back edges in a CFG indicate loops - || has_back_edge(&doms, node, &node_data) + || has_back_edge(doms, node, node_data) { Some(node) } else { diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index bb2a90a06da9..21b92e6d77c8 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -362,7 +362,7 @@ impl<'a, 'tcx> ConstAnalysis<'a, 'tcx> { && let Ok(rhs_layout) = self.tcx.layout_of(self.param_env.and(rhs_ty)) { let op = ImmTy::from_scalar(pointer, rhs_layout).into(); - self.assign_constant(state, place, op, &rhs.projection); + self.assign_constant(state, place, op, rhs.projection); } } Operand::Constant(box constant) => { diff --git a/compiler/rustc_mir_transform/src/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs index 59156b2427cc..d4e40a1b57ca 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drops.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drops.rs @@ -57,7 +57,7 @@ impl<'tcx> MirPass<'tcx> for ElaborateDrops { // For types that do not need dropping, the behaviour is trivial. So we only need to track // init/uninit for types that do need dropping. let move_data = - MoveData::gather_moves(&body, tcx, param_env, |ty| ty.needs_drop(tcx, param_env)); + MoveData::gather_moves(body, tcx, param_env, |ty| ty.needs_drop(tcx, param_env)); let elaborate_patch = { let env = MoveDataParamEnv { move_data, param_env }; @@ -67,7 +67,7 @@ impl<'tcx> MirPass<'tcx> for ElaborateDrops { .pass_name("elaborate_drops") .iterate_to_fixpoint() .into_results_cursor(body); - let dead_unwinds = compute_dead_unwinds(&body, &mut inits); + let dead_unwinds = compute_dead_unwinds(body, &mut inits); let uninits = MaybeUninitializedPlaces::new(tcx, body, &env) .mark_inactive_variants_as_uninit() diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index a42eacbf22b4..340bb1948ebf 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -14,7 +14,7 @@ pub struct FunctionItemReferences; impl<'tcx> MirLint<'tcx> for FunctionItemReferences { fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) { let mut checker = FunctionItemRefChecker { tcx, body }; - checker.visit_body(&body); + checker.visit_body(body); } } @@ -47,12 +47,12 @@ impl<'tcx> Visitor<'tcx> for FunctionItemRefChecker<'_, 'tcx> { for inner_ty in arg_ty.walk().filter_map(|arg| arg.as_type()) { if let Some((fn_id, fn_args)) = FunctionItemRefChecker::is_fn_ref(inner_ty) { - let span = self.nth_arg_span(&args, 0); + let span = self.nth_arg_span(args, 0); self.emit_lint(fn_id, fn_args, source_info, span); } } } else { - self.check_bound_args(def_id, args_ref, &args, source_info); + self.check_bound_args(def_id, args_ref, args, source_info); } } } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 7b5697bc9496..8fa267131843 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -280,7 +280,7 @@ impl<'tcx> Inliner<'tcx> { } let old_blocks = caller_body.basic_blocks.next_index(); - self.inline_call(caller_body, &callsite, callee_body); + self.inline_call(caller_body, callsite, callee_body); let new_blocks = old_blocks..caller_body.basic_blocks.next_index(); Ok(new_blocks) diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index fbcd6e75ad4f..7a844b01707d 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -35,12 +35,9 @@ impl<'tcx> MirPass<'tcx> for InstSimplify { } } - ctx.simplify_primitive_clone( - &mut block.terminator.as_mut().unwrap(), - &mut block.statements, - ); + ctx.simplify_primitive_clone(block.terminator.as_mut().unwrap(), &mut block.statements); ctx.simplify_intrinsic_assert( - &mut block.terminator.as_mut().unwrap(), + block.terminator.as_mut().unwrap(), &mut block.statements, ); simplify_duplicate_switch_targets(block.terminator.as_mut().unwrap()); diff --git a/compiler/rustc_mir_transform/src/jump_threading.rs b/compiler/rustc_mir_transform/src/jump_threading.rs index 22300ad24be7..5754dd08164e 100644 --- a/compiler/rustc_mir_transform/src/jump_threading.rs +++ b/compiler/rustc_mir_transform/src/jump_threading.rs @@ -95,7 +95,7 @@ impl<'tcx> MirPass<'tcx> for JumpThreading { let cost = CostChecker::new(tcx, param_env, None, body); - let mut state = State::new(ConditionSet::default(), &finder.map); + let mut state = State::new(ConditionSet::default(), finder.map); let conds = if let Some((value, then, else_)) = targets.as_static_if() { let Some(value) = ScalarInt::try_from_uint(value, discr_layout.size) else { @@ -112,7 +112,7 @@ impl<'tcx> MirPass<'tcx> for JumpThreading { })) }; let conds = ConditionSet(conds); - state.insert_value_idx(discr, conds, &finder.map); + state.insert_value_idx(discr, conds, finder.map); finder.find_opportunity(bb, state, cost, 0); } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index bf5f0ca7cbd2..a3a10b138c76 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -481,14 +481,14 @@ pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<' assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup)); // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled. - if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, &body)) { + if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) { pm::run_passes( tcx, body, &[&remove_uninit_drops::RemoveUninitDrops, &simplify::SimplifyCfg::RemoveFalseEdges], None, ); - check_consts::post_drop_elaboration::check_live_drops(tcx, &body); // FIXME: make this a MIR lint + check_consts::post_drop_elaboration::check_live_drops(tcx, body); // FIXME: make this a MIR lint } debug!("runtime_mir_lowering({:?})", did); diff --git a/compiler/rustc_mir_transform/src/pass_manager.rs b/compiler/rustc_mir_transform/src/pass_manager.rs index a8aba29adcd1..c4eca18ff277 100644 --- a/compiler/rustc_mir_transform/src/pass_manager.rs +++ b/compiler/rustc_mir_transform/src/pass_manager.rs @@ -99,7 +99,7 @@ where ); *polarity }); - overridden.unwrap_or_else(|| pass.is_enabled(&tcx.sess)) + overridden.unwrap_or_else(|| pass.is_enabled(tcx.sess)) } fn run_passes_inner<'tcx>( @@ -126,7 +126,7 @@ fn run_passes_inner<'tcx>( let dump_enabled = pass.is_mir_dump_enabled(); if dump_enabled { - dump_mir_for_pass(tcx, body, &name, false); + dump_mir_for_pass(tcx, body, name, false); } if validate { validate_body(tcx, body, format!("before pass {name}")); @@ -142,7 +142,7 @@ fn run_passes_inner<'tcx>( } if dump_enabled { - dump_mir_for_pass(tcx, body, &name, true); + dump_mir_for_pass(tcx, body, name, true); } if validate { validate_body(tcx, body, format!("after pass {name}")); diff --git a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs index 87fee2410eca..548879e2e39b 100644 --- a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs @@ -25,7 +25,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let param_env = tcx.param_env(body.source.def_id()); let move_data = - MoveData::gather_moves(&body, tcx, param_env, |ty| ty.needs_drop(tcx, param_env)); + MoveData::gather_moves(body, tcx, param_env, |ty| ty.needs_drop(tcx, param_env)); let mdpe = MoveDataParamEnv { move_data, param_env }; let mut maybe_inits = MaybeInitializedPlaces::new(tcx, body, &mdpe) diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index 0a1c011147ae..97d398fe5c91 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -74,7 +74,7 @@ pub fn simplify_cfg<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { impl<'tcx> MirPass<'tcx> for SimplifyCfg { fn name(&self) -> &'static str { - &self.name() + self.name() } fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index 7de4ca667949..a4ca2b91e829 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -167,7 +167,7 @@ impl<'tcx> ReplacementMap<'tcx> { }; let fields = self.fragments[place.local].as_ref()?; let (_, new_local) = fields[f]?; - Some(Place { local: new_local, projection: tcx.mk_place_elems(&rest) }) + Some(Place { local: new_local, projection: tcx.mk_place_elems(rest) }) } fn place_fragments( diff --git a/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs index 98f67e18a8d0..e68d37f4c701 100644 --- a/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs +++ b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs @@ -86,7 +86,7 @@ impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching { continue; } - let Some(discriminant_ty) = get_switched_on_type(&bb_data, tcx, body) else { continue }; + let Some(discriminant_ty) = get_switched_on_type(bb_data, tcx, body) else { continue }; let layout = tcx.layout_of( tcx.param_env_reveal_all_normalized(body.source.def_id()).and(discriminant_ty), diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 65bdcf107622..b882a038711c 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -740,7 +740,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { ) => { let fn_ty = operand.ty(self.body, self.tcx); let fn_ty = self.monomorphize(fn_ty); - visit_fn_use(self.tcx, fn_ty, false, span, &mut self.output); + visit_fn_use(self.tcx, fn_ty, false, span, self.output); } mir::Rvalue::Cast( mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_)), @@ -816,7 +816,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { let callee_ty = func.ty(self.body, tcx); let callee_ty = self.monomorphize(callee_ty); self.check_fn_args_move_size(callee_ty, args, location); - visit_fn_use(self.tcx, callee_ty, true, source, &mut self.output) + visit_fn_use(self.tcx, callee_ty, true, source, self.output) } mir::TerminatorKind::Drop { ref place, .. } => { let ty = place.ty(self.body, self.tcx).ty; @@ -828,7 +828,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { match *op { mir::InlineAsmOperand::SymFn { ref value } => { let fn_ty = self.monomorphize(value.const_.ty()); - visit_fn_use(self.tcx, fn_ty, false, source, &mut self.output); + visit_fn_use(self.tcx, fn_ty, false, source, self.output); } mir::InlineAsmOperand::SymStatic { def_id } => { let instance = Instance::mono(self.tcx, def_id); @@ -1118,7 +1118,7 @@ fn create_mono_items_for_vtable_methods<'tcx>( ) { assert!(!trait_ty.has_escaping_bound_vars() && !impl_ty.has_escaping_bound_vars()); - if let ty::Dynamic(ref trait_ty, ..) = trait_ty.kind() { + if let ty::Dynamic(trait_ty, ..) = trait_ty.kind() { if let Some(principal) = trait_ty.principal() { let poly_trait_ref = principal.with_self_ty(tcx, impl_ty); assert!(!poly_trait_ref.has_escaping_bound_vars()); @@ -1191,7 +1191,7 @@ impl<'v> RootCollector<'_, 'v> { // but even just declaring them must collect the items they refer to if let Ok(val) = self.tcx.const_eval_poly(id.owner_id.to_def_id()) { - collect_const_value(self.tcx, val, &mut self.output); + collect_const_value(self.tcx, val, self.output); } } DefKind::Impl { .. } => { @@ -1422,14 +1422,14 @@ fn collect_used_items<'tcx>( // and abort compilation if any of them errors. MirUsedCollector { tcx, - body: &body, + body: body, output, instance, move_size_spans: vec![], visiting_call_terminator: false, skip_move_check_fns: None, } - .visit_body(&body); + .visit_body(body); } #[instrument(skip(tcx, output), level = "debug")] diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index 4009e2892406..c2b307910e42 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -436,12 +436,12 @@ fn merge_codegen_units<'tcx>( for cgu in codegen_units.iter_mut() { if let Some(new_cgu_name) = new_cgu_names.get(&cgu.name()) { if cx.tcx.sess.opts.unstable_opts.human_readable_cgu_names { - cgu.set_name(Symbol::intern(&new_cgu_name)); + cgu.set_name(Symbol::intern(new_cgu_name)); } else { // If we don't require CGU names to be human-readable, // we use a fixed length hash of the composite CGU name // instead. - let new_cgu_name = CodegenUnit::mangle_name(&new_cgu_name); + let new_cgu_name = CodegenUnit::mangle_name(new_cgu_name); cgu.set_name(Symbol::intern(&new_cgu_name)); } } @@ -1140,7 +1140,7 @@ fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> (&DefIdSet, &[Co // Output monomorphization stats per def_id if let SwitchWithOptPath::Enabled(ref path) = tcx.sess.opts.unstable_opts.dump_mono_stats { if let Err(err) = - dump_mono_items_stats(tcx, &codegen_units, path, tcx.crate_name(LOCAL_CRATE)) + dump_mono_items_stats(tcx, codegen_units, path, tcx.crate_name(LOCAL_CRATE)) { tcx.sess.emit_fatal(CouldntDumpMonoStats { error: err.to_string() }); } diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index f2eed5c9be51..6e0765f74fec 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -75,7 +75,7 @@ pub(crate) fn parse_token_trees<'a>( let mut buffer = Vec::with_capacity(1); for unmatched in unmatched_delims { - if let Some(err) = make_unclosed_delims_error(unmatched, &sess) { + if let Some(err) = make_unclosed_delims_error(unmatched, sess) { err.buffer(&mut buffer); } } @@ -362,7 +362,7 @@ impl<'a> StringReader<'a> { if contains_text_flow_control_chars(content) { let span = self.mk_sp(start, self.pos); self.sess.buffer_lint_with_diagnostic( - &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, + TEXT_DIRECTION_CODEPOINT_IN_COMMENT, span, ast::CRATE_NODE_ID, "unicode codepoint changing visible direction of text present in comment", @@ -683,7 +683,7 @@ impl<'a> StringReader<'a> { } else { // Before Rust 2021, only emit a lint for migration. self.sess.buffer_lint_with_diagnostic( - &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, + RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, prefix_span, ast::CRATE_NODE_ID, format!("prefix `{prefix}` is unknown"), diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index db795ce9f723..e646f5dfd851 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -97,7 +97,7 @@ impl<'a> TokenTreesReader<'a> { report_suspicious_mismatch_block( &mut err, &self.diag_info, - &self.string_reader.sess.source_map(), + self.string_reader.sess.source_map(), *delim, ) } @@ -164,7 +164,7 @@ impl<'a> TokenTreesReader<'a> { unclosed_delimiter = Some(sp); }; for (brace, brace_span) in &self.diag_info.open_braces { - if same_indentation_level(&sm, self.token.span, *brace_span) + if same_indentation_level(sm, self.token.span, *brace_span) && brace == &close_delim { // high likelihood of these two corresponding @@ -271,7 +271,7 @@ impl<'a> TokenTreesReader<'a> { report_suspicious_mismatch_block( &mut err, &self.diag_info, - &self.string_reader.sess.source_map(), + self.string_reader.sess.source_map(), delim, ); err.span_label(self.token.span, "unexpected closing delimiter"); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 57bc865a0eed..ecb840f067eb 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1281,11 +1281,11 @@ impl<'a> Parser<'a> { (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => { let expr_to_str = |e: &Expr| { self.span_to_snippet(e.span) - .unwrap_or_else(|_| pprust::expr_to_string(&e)) + .unwrap_or_else(|_| pprust::expr_to_string(e)) }; err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison { span: inner_op.span.shrink_to_hi(), - middle_term: expr_to_str(&r1), + middle_term: expr_to_str(r1), }); false // Keep the current parse behavior, where the AST is `(x < y) < z`. } @@ -1506,7 +1506,7 @@ impl<'a> Parser<'a> { pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) { if impl_dyn_multi { - self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span }); + self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(ty), span: ty.span }); } } @@ -1939,7 +1939,7 @@ impl<'a> Parser<'a> { self.sess.emit_err(IncorrectAwait { span, sugg_span: (span, applicability), - expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)), + expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(expr)), question_mark: if is_question { "?" } else { "" }, }); diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index d8e99d34016e..79567eb38986 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1060,7 +1060,7 @@ impl<'a> Parser<'a> { match &*components { // 1e2 [IdentLike(i)] => { - DestructuredFloat::Single(Symbol::intern(&i), span) + DestructuredFloat::Single(Symbol::intern(i), span) } // 1. [IdentLike(i), Punct('.')] => { @@ -1072,7 +1072,7 @@ impl<'a> Parser<'a> { } else { (span, span) }; - let symbol = Symbol::intern(&i); + let symbol = Symbol::intern(i); DestructuredFloat::TrailingDot(symbol, ident_span, dot_span) } // 1.2 | 1.2e3 @@ -1088,8 +1088,8 @@ impl<'a> Parser<'a> { } else { (span, span, span) }; - let symbol1 = Symbol::intern(&i1); - let symbol2 = Symbol::intern(&i2); + let symbol1 = Symbol::intern(i1); + let symbol2 = Symbol::intern(i2); DestructuredFloat::MiddleDot(symbol1, ident1_span, dot_span, symbol2, ident2_span) } // 1e+ | 1e- (recovered) @@ -2052,7 +2052,7 @@ impl<'a> Parser<'a> { Err(err) => { let span = token.uninterpolated_span(); self.bump(); - report_lit_error(&self.sess, err, lit, span); + report_lit_error(self.sess, err, lit, span); // Pack possible quotes and prefixes from the original literal into // the error literal's symbol so they can be pretty-printed faithfully. let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None); @@ -3207,7 +3207,7 @@ impl<'a> Parser<'a> { if let Some((ident, _)) = self.token.ident() && !self.token.is_reserved_ident() && self.look_ahead(1, |t| { - AssocOp::from_token(&t).is_some() + AssocOp::from_token(t).is_some() || matches!(t.kind, token::OpenDelim(_)) || t.kind == token::Dot }) diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index d124ea571ab0..23886b1208bb 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -2271,7 +2271,7 @@ impl<'a> Parser<'a> { } else { &[token::Semi, token::OpenDelim(Delimiter::Brace)] }; - if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) { + if let Err(mut err) = self.expected_one_of_not_found(&[], expected) { if self.token.kind == token::CloseDelim(Delimiter::Brace) { // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in // the AST for typechecking. diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 5cec3f5762d7..15491cac56a7 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -541,7 +541,7 @@ impl<'a> Parser<'a> { } self.sess - .emit_err(AmbiguousRangePattern { span: pat.span, pat: pprust::pat_to_string(&pat) }); + .emit_err(AmbiguousRangePattern { span: pat.span, pat: pprust::pat_to_string(pat) }); } /// Parse `&pat` / `&mut pat`. @@ -641,7 +641,7 @@ impl<'a> Parser<'a> { self.sess.emit_err(if changed_any_binding { InvalidMutInPattern::NestedIdent { span: lo.to(pat.span), - pat: pprust::pat_to_string(&pat), + pat: pprust::pat_to_string(pat), } } else { InvalidMutInPattern::NonIdent { span: lo.until(pat.span) } diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index e6c46fc25283..cbe75b3dab6e 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -188,7 +188,7 @@ fn emit_malformed_attribute( } suggestions.sort(); if should_warn(name) { - sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, msg); + sess.buffer_lint(ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, msg); } else { sess.span_diagnostic .struct_span_err(span, error_msg) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index c5767fd902fa..4910d63010c6 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -130,59 +130,59 @@ impl CheckAttrVisitor<'_> { &mut specified_inline, &mut doc_aliases, ), - sym::no_link => self.check_no_link(hir_id, &attr, span, target), - sym::export_name => self.check_export_name(hir_id, &attr, span, target), + sym::no_link => self.check_no_link(hir_id, attr, span, target), + sym::export_name => self.check_export_name(hir_id, attr, span, target), sym::rustc_layout_scalar_valid_range_start | sym::rustc_layout_scalar_valid_range_end => { - self.check_rustc_layout_scalar_valid_range(&attr, span, target) + self.check_rustc_layout_scalar_valid_range(attr, span, target) } sym::allow_internal_unstable => { - self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs) + self.check_allow_internal_unstable(hir_id, attr, span, target, attrs) } - sym::debugger_visualizer => self.check_debugger_visualizer(&attr, target), + sym::debugger_visualizer => self.check_debugger_visualizer(attr, target), sym::rustc_allow_const_fn_unstable => { - self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target) + self.check_rustc_allow_const_fn_unstable(hir_id, attr, span, target) } sym::rustc_std_internal_symbol => { - self.check_rustc_std_internal_symbol(&attr, span, target) + self.check_rustc_std_internal_symbol(attr, span, target) } sym::naked => self.check_naked(hir_id, attr, span, target), sym::rustc_never_returns_null_ptr => { self.check_applied_to_fn_or_method(hir_id, attr, span, target) } sym::rustc_legacy_const_generics => { - self.check_rustc_legacy_const_generics(hir_id, &attr, span, target, item) + self.check_rustc_legacy_const_generics(hir_id, attr, span, target, item) } sym::rustc_lint_query_instability => { - self.check_rustc_lint_query_instability(hir_id, &attr, span, target) + self.check_rustc_lint_query_instability(hir_id, attr, span, target) } sym::rustc_lint_diagnostics => { - self.check_rustc_lint_diagnostics(hir_id, &attr, span, target) + self.check_rustc_lint_diagnostics(hir_id, attr, span, target) } - sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(&attr, span, target), + sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(attr, span, target), sym::rustc_lint_opt_deny_field_access => { - self.check_rustc_lint_opt_deny_field_access(&attr, span, target) + self.check_rustc_lint_opt_deny_field_access(attr, span, target) } sym::rustc_clean | sym::rustc_dirty | sym::rustc_if_this_changed - | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr), + | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(attr), sym::rustc_coinductive | sym::rustc_must_implement_one_of | sym::rustc_deny_explicit_impl - | sym::const_trait => self.check_must_be_applied_to_trait(&attr, span, target), + | sym::const_trait => self.check_must_be_applied_to_trait(attr, span, target), sym::cmse_nonsecure_entry => { self.check_cmse_nonsecure_entry(hir_id, attr, span, target) } sym::collapse_debuginfo => self.check_collapse_debuginfo(attr, span, target), - sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target), - sym::must_use => self.check_must_use(hir_id, &attr, target), - sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target), + sym::must_not_suspend => self.check_must_not_suspend(attr, span, target), + sym::must_use => self.check_must_use(hir_id, attr, target), + sym::rustc_pass_by_value => self.check_pass_by_value(attr, span, target), sym::rustc_allow_incoherent_impl => { - self.check_allow_incoherent_impl(&attr, span, target) + self.check_allow_incoherent_impl(attr, span, target) } sym::rustc_has_incoherent_inherent_impls => { - self.check_has_incoherent_inherent_impls(&attr, span, target) + self.check_has_incoherent_inherent_impls(attr, span, target) } sym::ffi_pure => self.check_ffi_pure(attr.span, attrs, target), sym::ffi_const => self.check_ffi_const(attr.span, target), @@ -192,9 +192,9 @@ impl CheckAttrVisitor<'_> { | sym::unstable | sym::stable | sym::rustc_allowed_through_unstable_modules - | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target), - sym::link_ordinal => self.check_link_ordinal(&attr, span, target), - sym::rustc_confusables => self.check_confusables(&attr, target), + | sym::rustc_promotable => self.check_stability_promotable(attr, span, target), + sym::link_ordinal => self.check_link_ordinal(attr, span, target), + sym::rustc_confusables => self.check_confusables(attr, target), sym::rustc_safe_intrinsic => { self.check_rustc_safe_intrinsic(hir_id, attr, span, target) } @@ -824,7 +824,7 @@ impl CheckAttrVisitor<'_> { hir::Node::Item(item) => Some(&item.kind), _ => None, }) { - Some(ItemKind::Mod(ref module)) => { + Some(ItemKind::Mod(module)) => { if !module.item_ids.is_empty() { self.tcx.sess.emit_err(errors::DocKeywordEmptyMod { span: meta.span() }); return false; @@ -850,7 +850,7 @@ impl CheckAttrVisitor<'_> { hir::Node::Item(item) => Some(&item.kind), _ => None, }) { - Some(ItemKind::Impl(ref i)) => { + Some(ItemKind::Impl(i)) => { let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_])) || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind { bare_fn_ty.decl.inputs.len() == 1 @@ -2395,7 +2395,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { // Historically we've run more checks on non-exported than exported macros, // so this lets us continue to run them while maintaining backwards compatibility. // In the long run, the checks should be harmonized. - if let ItemKind::Macro(ref macro_def, _) = item.kind { + if let ItemKind::Macro(macro_def, _) = item.kind { let def_id = item.owner_id.to_def_id(); if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) { check_non_exported_macro_for_invalid_attrs(self.tcx, item); @@ -2443,7 +2443,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) { // When checking statements ignore expressions, they will be checked later. - if let hir::StmtKind::Local(ref l) = stmt.kind { + if let hir::StmtKind::Local(l) = stmt.kind { self.check_attributes(l.hir_id, stmt.span, Target::Statement, None); } intravisit::walk_stmt(self, stmt) diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index 7188c177feba..22b80a60d42a 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -111,7 +111,7 @@ impl<'tcx> CheckConstVisitor<'tcx> { // However, we cannot allow stable `const fn`s to use unstable features without an explicit // opt-in via `rustc_allow_const_fn_unstable`. let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id)); - attr::rustc_allow_const_fn_unstable(&tcx.sess, attrs).any(|name| name == feature_gate) + attr::rustc_allow_const_fn_unstable(tcx.sess, attrs).any(|name| name == feature_gate) }; match required_gates { diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 6b2b842543a8..b4ebc2db3d60 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -373,10 +373,10 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { self.repr_has_repr_c = def.repr().c(); self.repr_has_repr_simd = def.repr().simd(); - intravisit::walk_item(self, &item) + intravisit::walk_item(self, item) } hir::ItemKind::ForeignMod { .. } => {} - _ => intravisit::walk_item(self, &item), + _ => intravisit::walk_item(self, item), }, Node::TraitItem(trait_item) => { intravisit::walk_trait_item(self, trait_item); @@ -403,7 +403,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { intravisit::walk_impl_item(self, impl_item); } Node::ForeignItem(foreign_item) => { - intravisit::walk_foreign_item(self, &foreign_item); + intravisit::walk_foreign_item(self, foreign_item); } _ => {} } @@ -459,9 +459,9 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { self.lookup_and_handle_method(expr.hir_id); } hir::ExprKind::Field(ref lhs, ..) => { - self.handle_field_access(&lhs, expr.hir_id); + self.handle_field_access(lhs, expr.hir_id); } - hir::ExprKind::Struct(ref qpath, ref fields, _) => { + hir::ExprKind::Struct(qpath, fields, _) => { let res = self.typeck_results().qpath_res(qpath, expr.hir_id); self.handle_res(res); if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() { @@ -493,7 +493,7 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { self.in_pat = true; match pat.kind { - PatKind::Struct(ref path, ref fields, _) => { + PatKind::Struct(ref path, fields, _) => { let res = self.typeck_results().qpath_res(path, pat.hir_id); self.handle_field_pattern_match(pat, res, fields); } @@ -501,7 +501,7 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { let res = self.typeck_results().qpath_res(qpath, pat.hir_id); self.handle_res(res); } - PatKind::TupleStruct(ref qpath, ref fields, dotdot) => { + PatKind::TupleStruct(ref qpath, fields, dotdot) => { let res = self.typeck_results().qpath_res(qpath, pat.hir_id); self.handle_tuple_field_pattern_match(pat, res, fields, dotdot); } @@ -1011,7 +1011,7 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) { let def_id = field.did.expect_local(); let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); if let ShouldWarnAboutField::Yes(is_pos) = - visitor.should_warn_about_field(&field) + visitor.should_warn_about_field(field) { let level = tcx .lint_level_at_node( diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index 51a64b3855fd..2629b2817565 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -38,7 +38,7 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> { } // If the user wants no main function at all, then stop here. - if attr::contains_name(&tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) { + if attr::contains_name(tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) { return None; } diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index 2aec4ea7ef13..f78157f89ae3 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -43,7 +43,7 @@ impl<'tcx> LanguageItemCollector<'tcx> { fn check_for_lang(&mut self, actual_target: Target, def_id: LocalDefId) { let attrs = self.tcx.hir().attrs(self.tcx.hir().local_def_id_to_hir_id(def_id)); - if let Some((name, span)) = extract(&attrs) { + if let Some((name, span)) = extract(attrs) { match LangItem::from_name(name) { // Known lang item with attribute on correct target. Some(lang_item) if actual_target == lang_item.target() => { diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index b73fb984c0ea..a0ba4e481f6b 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -170,7 +170,7 @@ fn check_liveness(tcx: TyCtxt<'_>, def_id: LocalDefId) { // compute liveness let mut lsets = Liveness::new(&mut maps, def_id); - let entry_ln = lsets.compute(&body, hir_id); + let entry_ln = lsets.compute(body, hir_id); lsets.log_liveness(entry_ln, body_id.hir_id); // check for various error conditions @@ -366,7 +366,7 @@ impl<'tcx> IrMaps<'tcx> { impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { - self.add_from_pat(&local.pat); + self.add_from_pat(local.pat); if local.els.is_some() { self.add_live_node_for_node(local.hir_id, ExprNode(local.span, local.hir_id)); } @@ -374,8 +374,8 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { } fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { - self.add_from_pat(&arm.pat); - if let Some(hir::Guard::IfLet(ref let_expr)) = arm.guard { + self.add_from_pat(arm.pat); + if let Some(hir::Guard::IfLet(let_expr)) = arm.guard { self.add_from_pat(let_expr.pat); } intravisit::walk_arm(self, arm); @@ -400,7 +400,7 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) { match expr.kind { // live nodes required for uses or definitions of variables: - hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { + hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => { debug!("expr {}: path that leads to {:?}", expr.hir_id, path.res); if let Res::Local(_var_hir_id) = path.res { self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id)); @@ -736,7 +736,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } } - let succ = self.propagate_through_expr(&body.value, self.exit_ln); + let succ = self.propagate_through_expr(body.value, self.exit_ln); if self.closure_min_captures.is_none() { // Either not a closure, or closure without any captured variables. @@ -776,7 +776,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { if !self.merge_from_succ(self.exit_ln, self.closure_ln) { break; } - assert_eq!(succ, self.propagate_through_expr(&body.value, self.exit_ln)); + assert_eq!(succ, self.propagate_through_expr(body.value, self.exit_ln)); } succ @@ -792,7 +792,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { fn propagate_through_stmt(&mut self, stmt: &hir::Stmt<'_>, succ: LiveNode) -> LiveNode { match stmt.kind { - hir::StmtKind::Local(ref local) => { + hir::StmtKind::Local(local) => { // Note: we mark the variable as defined regardless of whether // there is an initializer. Initially I had thought to only mark // the live variable as defined if it was initialized, and then we @@ -830,7 +830,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { self.init_from_succ(ln, succ); self.merge_from_succ(ln, else_ln); let succ = self.propagate_through_expr(init, ln); - self.define_bindings_in_pat(&local.pat, succ) + self.define_bindings_in_pat(local.pat, succ) } else { span_bug!( stmt.span, @@ -839,18 +839,18 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } } else { let succ = self.propagate_through_opt_expr(local.init, succ); - self.define_bindings_in_pat(&local.pat, succ) + self.define_bindings_in_pat(local.pat, succ) } } hir::StmtKind::Item(..) => succ, hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => { - self.propagate_through_expr(&expr, succ) + self.propagate_through_expr(expr, succ) } } } fn propagate_through_exprs(&mut self, exprs: &[Expr<'_>], succ: LiveNode) -> LiveNode { - exprs.iter().rev().fold(succ, |succ, expr| self.propagate_through_expr(&expr, succ)) + exprs.iter().rev().fold(succ, |succ, expr| self.propagate_through_expr(expr, succ)) } fn propagate_through_opt_expr( @@ -866,11 +866,11 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { match expr.kind { // Interesting cases with control flow or which gen/kill - hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { + hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => { self.access_path(expr.hir_id, path, succ, ACC_READ | ACC_USE) } - hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(&e, succ), + hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(e, succ), hir::ExprKind::Closure { .. } => { debug!("{:?} is an ExprKind::Closure", expr); @@ -899,9 +899,9 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // Note that labels have been resolved, so we don't need to look // at the label ident - hir::ExprKind::Loop(ref blk, ..) => self.propagate_through_loop(expr, &blk, succ), + hir::ExprKind::Loop(ref blk, ..) => self.propagate_through_loop(expr, blk, succ), - hir::ExprKind::Yield(ref e, ..) => { + hir::ExprKind::Yield(e, ..) => { let yield_ln = self.live_node(expr.hir_id, expr.span); self.init_from_succ(yield_ln, succ); self.merge_from_succ(yield_ln, self.exit_ln); @@ -923,11 +923,11 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // ( succ ) // let else_ln = self.propagate_through_opt_expr(else_opt.as_deref(), succ); - let then_ln = self.propagate_through_expr(&then, succ); + let then_ln = self.propagate_through_expr(then, succ); let ln = self.live_node(expr.hir_id, expr.span); self.init_from_succ(ln, else_ln); self.merge_from_succ(ln, then_ln); - self.propagate_through_expr(&cond, ln) + self.propagate_through_expr(cond, ln) } hir::ExprKind::Match(ref e, arms, _) => { @@ -948,7 +948,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let ln = self.live_node(expr.hir_id, expr.span); self.init_empty(ln, succ); for arm in arms { - let body_succ = self.propagate_through_expr(&arm.body, succ); + let body_succ = self.propagate_through_expr(arm.body, succ); let guard_succ = arm.guard.as_ref().map_or(body_succ, |g| match g { hir::Guard::If(e) => self.propagate_through_expr(e, body_succ), @@ -957,10 +957,10 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { self.propagate_through_expr(let_expr.init, let_bind) } }); - let arm_succ = self.define_bindings_in_pat(&arm.pat, guard_succ); + let arm_succ = self.define_bindings_in_pat(arm.pat, guard_succ); self.merge_from_succ(ln, arm_succ); } - self.propagate_through_expr(&e, ln) + self.propagate_through_expr(e, ln) } hir::ExprKind::Ret(ref o_e) => { @@ -968,7 +968,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { self.propagate_through_opt_expr(o_e.as_deref(), self.exit_ln) } - hir::ExprKind::Become(ref e) => { + hir::ExprKind::Become(e) => { // Ignore succ and subst exit_ln. self.propagate_through_expr(e, self.exit_ln) } @@ -1007,63 +1007,63 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { hir::ExprKind::Assign(ref l, ref r, _) => { // see comment on places in // propagate_through_place_components() - let succ = self.write_place(&l, succ, ACC_WRITE); - let succ = self.propagate_through_place_components(&l, succ); - self.propagate_through_expr(&r, succ) + let succ = self.write_place(l, succ, ACC_WRITE); + let succ = self.propagate_through_place_components(l, succ); + self.propagate_through_expr(r, succ) } hir::ExprKind::AssignOp(_, ref l, ref r) => { // an overloaded assign op is like a method call if self.typeck_results.is_method_call(expr) { - let succ = self.propagate_through_expr(&l, succ); - self.propagate_through_expr(&r, succ) + let succ = self.propagate_through_expr(l, succ); + self.propagate_through_expr(r, succ) } else { // see comment on places in // propagate_through_place_components() - let succ = self.write_place(&l, succ, ACC_WRITE | ACC_READ); - let succ = self.propagate_through_expr(&r, succ); - self.propagate_through_place_components(&l, succ) + let succ = self.write_place(l, succ, ACC_WRITE | ACC_READ); + let succ = self.propagate_through_expr(r, succ); + self.propagate_through_place_components(l, succ) } } // Uninteresting cases: just propagate in rev exec order - hir::ExprKind::Array(ref exprs) => self.propagate_through_exprs(exprs, succ), + hir::ExprKind::Array(exprs) => self.propagate_through_exprs(exprs, succ), - hir::ExprKind::Struct(_, ref fields, ref with_expr) => { + hir::ExprKind::Struct(_, fields, ref with_expr) => { let succ = self.propagate_through_opt_expr(with_expr.as_deref(), succ); fields .iter() .rev() - .fold(succ, |succ, field| self.propagate_through_expr(&field.expr, succ)) + .fold(succ, |succ, field| self.propagate_through_expr(field.expr, succ)) } - hir::ExprKind::Call(ref f, ref args) => { + hir::ExprKind::Call(ref f, args) => { let succ = self.check_is_ty_uninhabited(expr, succ); let succ = self.propagate_through_exprs(args, succ); - self.propagate_through_expr(&f, succ) + self.propagate_through_expr(f, succ) } - hir::ExprKind::MethodCall(.., receiver, ref args, _) => { + hir::ExprKind::MethodCall(.., receiver, args, _) => { let succ = self.check_is_ty_uninhabited(expr, succ); let succ = self.propagate_through_exprs(args, succ); self.propagate_through_expr(receiver, succ) } - hir::ExprKind::Tup(ref exprs) => self.propagate_through_exprs(exprs, succ), + hir::ExprKind::Tup(exprs) => self.propagate_through_exprs(exprs, succ), hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => { - let r_succ = self.propagate_through_expr(&r, succ); + let r_succ = self.propagate_through_expr(r, succ); let ln = self.live_node(expr.hir_id, expr.span); self.init_from_succ(ln, succ); self.merge_from_succ(ln, r_succ); - self.propagate_through_expr(&l, ln) + self.propagate_through_expr(l, ln) } hir::ExprKind::Index(ref l, ref r, _) | hir::ExprKind::Binary(_, ref l, ref r) => { - let r_succ = self.propagate_through_expr(&r, succ); - self.propagate_through_expr(&l, r_succ) + let r_succ = self.propagate_through_expr(r, succ); + self.propagate_through_expr(l, r_succ) } hir::ExprKind::AddrOf(_, _, ref e) @@ -1071,9 +1071,9 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { | hir::ExprKind::Type(ref e, _) | hir::ExprKind::DropTemps(ref e) | hir::ExprKind::Unary(_, ref e) - | hir::ExprKind::Repeat(ref e, _) => self.propagate_through_expr(&e, succ), + | hir::ExprKind::Repeat(ref e, _) => self.propagate_through_expr(e, succ), - hir::ExprKind::InlineAsm(ref asm) => { + hir::ExprKind::InlineAsm(asm) => { // Handle non-returning asm let mut succ = if asm.options.contains(InlineAsmOptions::NORETURN) { self.exit_ln @@ -1141,7 +1141,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // Note that labels have been resolved, so we don't need to look // at the label ident - hir::ExprKind::Block(ref blk, _) => self.propagate_through_block(&blk, succ), + hir::ExprKind::Block(ref blk, _) => self.propagate_through_block(blk, succ), } } @@ -1197,7 +1197,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { match expr.kind { hir::ExprKind::Path(_) => succ, - hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(&e, succ), + hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(e, succ), _ => self.propagate_through_expr(expr, succ), } } @@ -1205,7 +1205,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // see comment on propagate_through_place() fn write_place(&mut self, expr: &Expr<'_>, succ: LiveNode, acc: u32) -> LiveNode { match expr.kind { - hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { + hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => { self.access_path(expr.hir_id, path, succ, acc) } @@ -1341,7 +1341,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> { fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { - self.check_unused_vars_in_pat(&local.pat, None, None, |spans, hir_id, ln, var| { + self.check_unused_vars_in_pat(local.pat, None, None, |spans, hir_id, ln, var| { if local.init.is_some() { self.warn_about_dead_assign(spans, hir_id, ln, var); } @@ -1356,7 +1356,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> { } fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { - self.check_unused_vars_in_pat(&arm.pat, None, None, |_, _, _, _| {}); + self.check_unused_vars_in_pat(arm.pat, None, None, |_, _, _, _| {}); intravisit::walk_arm(self, arm); } } @@ -1364,16 +1364,16 @@ impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> { fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) { match expr.kind { hir::ExprKind::Assign(ref l, ..) => { - this.check_place(&l); + this.check_place(l); } hir::ExprKind::AssignOp(_, ref l, _) => { if !this.typeck_results.is_method_call(expr) { - this.check_place(&l); + this.check_place(l); } } - hir::ExprKind::InlineAsm(ref asm) => { + hir::ExprKind::InlineAsm(asm) => { for (op, _op_sp) in asm.operands { match op { hir::InlineAsmOperand::Out { expr, .. } => { @@ -1434,7 +1434,7 @@ fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) { impl<'tcx> Liveness<'_, 'tcx> { fn check_place(&mut self, expr: &'tcx Expr<'tcx>) { match expr.kind { - hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { + hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => { if let Res::Local(var_hid) = path.res { // Assignment to an immutable variable or argument: only legal // if there is no later assignment. If this local is actually @@ -1507,7 +1507,7 @@ impl<'tcx> Liveness<'_, 'tcx> { fn warn_about_unused_args(&self, body: &hir::Body<'_>, entry_ln: LiveNode) { for p in body.params { self.check_unused_vars_in_pat( - &p.pat, + p.pat, Some(entry_ln), Some(body), |spans, hir_id, ln, var| { diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index 25e131d7477f..8e6d58052756 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -39,7 +39,7 @@ struct CheckLoopVisitor<'a, 'hir> { fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { tcx.hir().visit_item_likes_in_module( module_def_id, - &mut CheckLoopVisitor { sess: &tcx.sess, hir_map: tcx.hir(), cx: Normal }, + &mut CheckLoopVisitor { sess: tcx.sess, hir_map: tcx.hir(), cx: Normal }, ); } @@ -84,7 +84,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) { match e.kind { hir::ExprKind::Loop(ref b, _, source, _) => { - self.with_context(Loop(source), |v| v.visit_block(&b)); + self.with_context(Loop(source), |v| v.visit_block(b)); } hir::ExprKind::Closure(&hir::Closure { ref fn_decl, @@ -98,19 +98,19 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { } else { Closure(fn_decl_span) }; - self.visit_fn_decl(&fn_decl); + self.visit_fn_decl(fn_decl); self.with_context(cx, |v| v.visit_nested_body(body)); } hir::ExprKind::Block(ref b, Some(_label)) => { - self.with_context(LabeledBlock, |v| v.visit_block(&b)); + self.with_context(LabeledBlock, |v| v.visit_block(b)); } hir::ExprKind::Block(ref b, None) if matches!(self.cx, Fn) => { - self.with_context(Normal, |v| v.visit_block(&b)); + self.with_context(Normal, |v| v.visit_block(b)); } hir::ExprKind::Block(ref b, None) if matches!(self.cx, Normal | Constant | UnlabeledBlock(_)) => { - self.with_context(UnlabeledBlock(b.span.shrink_to_lo()), |v| v.visit_block(&b)); + self.with_context(UnlabeledBlock(b.span.shrink_to_lo()), |v| v.visit_block(b)); } hir::ExprKind::Break(break_label, ref opt_expr) => { if let Some(e) = opt_expr { diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index 7f36c59ad98d..54f296da5c53 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -211,7 +211,7 @@ impl<'tcx> CheckInlineAssembly<'tcx> { self.items.push((ItemKind::NonAsm, span)); } - ExprKind::InlineAsm(ref asm) => { + ExprKind::InlineAsm(asm) => { self.items.push((ItemKind::Asm, span)); self.check_inline_asm(asm, span); } @@ -282,13 +282,13 @@ impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> { StmtKind::Local(..) => { self.items.push((ItemKind::NonAsm, stmt.span)); } - StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => { + StmtKind::Expr(expr) | StmtKind::Semi(expr) => { self.check_expr(expr, stmt.span); } } } fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { - self.check_expr(&expr, expr.span); + self.check_expr(expr, expr.span); } } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 03070dc6f28d..fd7cf1ac11e3 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -158,9 +158,9 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { return; } - let stab = attr::find_stability(&self.tcx.sess, attrs, item_sp); - let const_stab = attr::find_const_stability(&self.tcx.sess, attrs, item_sp); - let body_stab = attr::find_body_stability(&self.tcx.sess, attrs); + let stab = attr::find_stability(self.tcx.sess, attrs, item_sp); + let const_stab = attr::find_const_stability(self.tcx.sess, attrs, item_sp); + let body_stab = attr::find_body_stability(self.tcx.sess, attrs); let mut const_span = None; let const_stab = const_stab.map(|(const_stab, const_span_node)| { @@ -721,8 +721,8 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { let features = self.tcx.features(); if features.staged_api { let attrs = self.tcx.hir().attrs(item.hir_id()); - let stab = attr::find_stability(&self.tcx.sess, attrs, item.span); - let const_stab = attr::find_const_stability(&self.tcx.sess, attrs, item.span); + let stab = attr::find_stability(self.tcx.sess, attrs, item.span); + let const_stab = attr::find_const_stability(self.tcx.sess, attrs, item.span); // If this impl block has an #[unstable] attribute, give an // error if all involved types and traits are stable, because diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index a14c2916392d..4324afe42b38 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -664,7 +664,7 @@ impl<'tcx> EmbargoVisitor<'tcx> { impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { if self.impl_trait_pass - && let hir::ItemKind::OpaqueTy(ref opaque) = item.kind + && let hir::ItemKind::OpaqueTy(opaque) = item.kind && !opaque.in_trait { // FIXME: This is some serious pessimization intended to workaround deficiencies @@ -688,7 +688,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { | hir::ItemKind::GlobalAsm(..) => {} // The interface is empty, and all nested items are processed by `visit_item`. hir::ItemKind::Mod(..) | hir::ItemKind::OpaqueTy(..) => {} - hir::ItemKind::Macro(ref macro_def, _) => { + hir::ItemKind::Macro(macro_def, _) => { if let Some(item_ev) = item_ev { self.update_reachability_from_macro(item.owner_id.def_id, macro_def, item_ev); } @@ -727,7 +727,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { self.reach(item.owner_id.def_id, item_ev).generics().predicates(); } } - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl(impl_) => { // Type inference is very smart sometimes. It can make an impl reachable even some // components of its type or trait are unreachable. E.g. methods of // `impl ReachableTrait for ReachableTy { ... }` @@ -1741,7 +1741,7 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx, '_> { // Subitems of trait impls have inherited publicity. DefKind::Impl { .. } => { let item = tcx.hir().item(id); - if let hir::ItemKind::Impl(ref impl_) = item.kind { + if let hir::ItemKind::Impl(impl_) = item.kind { let impl_vis = ty::Visibility::of_impl::( item.owner_id.def_id, tcx, diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 6ad72e37a8c4..a290bd10bea0 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -358,7 +358,7 @@ pub(crate) fn encode_query_results<'a, 'tcx, Q>( assert!(query.query_state(qcx).all_inactive()); let cache = query.query_cache(qcx); cache.iter(&mut |key, value, dep_node| { - if query.cache_on_disk(qcx.tcx, &key) { + if query.cache_on_disk(qcx.tcx, key) { let dep_node = SerializedDepNodeIndex::new(dep_node.index()); // Record position of the cache entry. diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 831062b1678f..d720744a7a74 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -743,7 +743,7 @@ impl DepGraphData { // in the previous compilation session too, so we can try to // mark it as green by recursively marking all of its // dependencies green. - self.try_mark_previous_green(qcx, prev_index, &dep_node, None) + self.try_mark_previous_green(qcx, prev_index, dep_node, None) .map(|dep_node_index| (prev_index, dep_node_index)) } } diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 1f3403d09be6..6c08df99e9da 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -220,7 +220,7 @@ where C: QueryCache, Tcx: DepContext, { - match cache.lookup(&key) { + match cache.lookup(key) { Some((value, index)) => { tcx.profiler().query_cache_hit(index.into()); tcx.dep_graph().read_index(index); @@ -502,7 +502,7 @@ where // The diagnostics for this query will be promoted to the current session during // `try_mark_green()`, so we can ignore them here. if let Some(ret) = qcx.start_query(job_id, false, None, || { - try_load_from_disk_and_cache_in_memory(query, dep_graph_data, qcx, &key, &dep_node) + try_load_from_disk_and_cache_in_memory(query, dep_graph_data, qcx, &key, dep_node) }) { return ret; } @@ -563,7 +563,7 @@ where // Note this function can be called concurrently from the same query // We must ensure that this is handled correctly. - let (prev_dep_node_index, dep_node_index) = dep_graph_data.try_mark_green(qcx, &dep_node)?; + let (prev_dep_node_index, dep_node_index) = dep_graph_data.try_mark_green(qcx, dep_node)?; debug_assert!(dep_graph_data.is_index_green(prev_dep_node_index)); @@ -610,7 +610,7 @@ where // Sanity check for the logic in `ensure`: if the node is green and the result loadable, // we should actually be able to load it. debug_assert!( - !query.loadable_from_disk(qcx, &key, prev_dep_node_index), + !query.loadable_from_disk(qcx, key, prev_dep_node_index), "missing on-disk cache entry for loadable {dep_node:?}" ); @@ -667,7 +667,7 @@ pub(crate) fn incremental_verify_ich( let old_hash = dep_graph_data.prev_fingerprint_of(prev_index); if new_hash != old_hash { - incremental_verify_ich_failed(tcx, prev_index, &|| format_value(&result)); + incremental_verify_ich_failed(tcx, prev_index, &|| format_value(result)); } } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 0407db528af6..0b1a43f32826 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -123,7 +123,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { .map(|parent_id| self.get_nearest_non_block_module(parent_id)); // Query `expn_that_defined` is not used because // hashing spans in its result is expensive. - let expn_id = self.cstore().expn_that_defined_untracked(def_id, &self.tcx.sess); + let expn_id = self.cstore().expn_that_defined_untracked(def_id, self.tcx.sess); return Some(self.new_module( parent, ModuleKind::Def(def_kind, def_id, self.tcx.item_name(def_id)), diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 84225bbe39b2..863834a122e5 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -979,7 +979,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { path_span: path.span, // intentionally converting to String, as the text would also be used as // in suggestion context - path_str: pprust::path_to_string(&path), + path_str: pprust::path_to_string(path), }) } VisResolutionError::AncestorOnly(span) => { @@ -1444,7 +1444,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if let Ok(binding) = self.early_resolve_ident_in_lexical_scope( ident, ScopeSet::All(ns), - &parent_scope, + parent_scope, None, false, None, diff --git a/compiler/rustc_resolve/src/effective_visibilities.rs b/compiler/rustc_resolve/src/effective_visibilities.rs index 4477b9672831..a71c50dd82fd 100644 --- a/compiler/rustc_resolve/src/effective_visibilities.rs +++ b/compiler/rustc_resolve/src/effective_visibilities.rs @@ -115,7 +115,7 @@ impl<'r, 'a, 'tcx> EffectiveVisibilitiesVisitor<'r, 'a, 'tcx> { /// Update effective visibilities of bindings in the given module, /// including their whole reexport chains. fn set_bindings_effective_visibilities(&mut self, module_id: LocalDefId) { - assert!(self.r.module_map.contains_key(&&module_id.to_def_id())); + assert!(self.r.module_map.contains_key(&module_id.to_def_id())); let module = self.r.get_module(module_id.to_def_id()).unwrap(); let resolutions = self.r.resolutions(module); diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index b34790a925ea..3774ae664200 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -708,7 +708,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.tcx, &mut diag, Some(err.span), - &candidates, + candidates, DiagnosticMode::Import, (source != target) .then(|| format!(" as {target}")) @@ -720,7 +720,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.tcx, &mut diag, None, - &candidates, + candidates, DiagnosticMode::Normal, (source != target) .then(|| format!(" as {target}")) diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 9b7897d69e78..75a0541b89be 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -739,7 +739,7 @@ impl<'a: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast, } TyKind::Path(qself, path) => { self.diagnostic_metadata.current_type_path = Some(ty); - self.smart_resolve_path(ty.id, &qself, path, PathSource::Type); + self.smart_resolve_path(ty.id, qself, path, PathSource::Type); // Check whether we should interpret this as a bare trait object. if qself.is_none() @@ -759,7 +759,7 @@ impl<'a: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast, kind: LifetimeBinderKind::PolyTrait, span, }, - |this| this.visit_path(&path, ty.id), + |this| this.visit_path(path, ty.id), ); } else { visit::walk_ty(self, ty) @@ -1043,7 +1043,7 @@ impl<'a: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast, ClosureBinder::NotPresent => {} ClosureBinder::For { generic_params, .. } => { self.visit_generic_params( - &generic_params, + generic_params, self.diagnostic_metadata.current_self_item.is_some(), ); } @@ -1187,7 +1187,7 @@ impl<'a: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast, { let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo()); this.with_generic_param_rib( - &bound_generic_params, + bound_generic_params, RibKind::Normal, LifetimeRibKind::Generics { binder: bounded_ty.id, @@ -1195,7 +1195,7 @@ impl<'a: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast, span, }, |this| { - this.visit_generic_params(&bound_generic_params, false); + this.visit_generic_params(bound_generic_params, false); this.visit_ty(bounded_ty); for bound in bounds { this.visit_param_bound(bound, BoundKind::Bound) @@ -1997,7 +1997,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { } else { LifetimeRibKind::ElisionFailure }; - self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty)); + self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty)); let elision_failures = replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures); if !elision_failures.is_empty() { @@ -2379,7 +2379,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { &item.attrs, generics, of_trait, - &self_ty, + self_ty, item.id, impl_items, ); @@ -2743,7 +2743,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { /// When evaluating a `trait` use its associated types' idents for suggestions in E0412. fn resolve_trait_items(&mut self, trait_items: &'ast [P]) { let trait_assoc_items = - replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items)); + replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(trait_items)); let walk_assoc_item = |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| { @@ -3945,7 +3945,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { ))); } - let result = match self.resolve_path(&path, Some(ns), Some(finalize)) { + let result = match self.resolve_path(path, Some(ns), Some(finalize)) { PathResult::NonModule(path_res) => path_res, PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => { PartialRes::new(module.res().unwrap()) @@ -4208,7 +4208,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { ExprKind::Break(None, Some(ref e)) => { // We use this instead of `visit::walk_expr` to keep the parent expr around for // better diagnostics. - self.resolve_expr(e, Some(&expr)); + self.resolve_expr(e, Some(expr)); } ExprKind::Let(ref pat, ref scrutinee, _, _) => { @@ -4229,7 +4229,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { } ExprKind::Loop(ref block, label, _) => { - self.resolve_labeled_block(label, expr.id, &block) + self.resolve_labeled_block(label, expr.id, block) } ExprKind::While(ref cond, ref block, label) => { @@ -4318,7 +4318,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { .. }) => { self.with_generic_param_rib( - &generic_params, + generic_params, RibKind::Normal, LifetimeRibKind::Generics { binder: expr.id, diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index d62d7fdcae0c..4587ad14db7a 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -906,7 +906,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { } // If the trait has a single item (which wasn't matched by the algorithm), suggest it - let suggestion = self.get_single_associated_item(&path, &source, is_expected); + let suggestion = self.get_single_associated_item(path, &source, is_expected); if !self.r.add_typo_suggestion(err, suggestion, ident_span) { fallback = !self.let_binding_suggestion(err, ident_span); } @@ -1397,7 +1397,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { match source { PathSource::Expr(Some( parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. }, - )) if path_sep(this, err, &parent, DefKind::Struct) => {} + )) if path_sep(this, err, parent, DefKind::Struct) => {} PathSource::Expr( None | Some(Expr { @@ -1556,7 +1556,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { Res::Def(kind @ (DefKind::Mod | DefKind::Trait), _), PathSource::Expr(Some(parent)), ) => { - if !path_sep(self, err, &parent, kind) { + if !path_sep(self, err, parent, kind) { return false; } } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 2ff6fb424e67..7242aa890f82 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -371,7 +371,7 @@ impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> { if opt_ext.is_none() { *opt_ext = Some( match self.resolve_macro_path( - &path, + path, Some(MacroKind::Derive), &parent_scope, true, @@ -485,7 +485,7 @@ impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> { } fn registered_tools(&self) -> &RegisteredTools { - &self.registered_tools + self.registered_tools } } @@ -887,7 +887,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } } if let Some(depr) = &ext.deprecation { - let path = pprust::path_to_string(&path); + let path = pprust::path_to_string(path); let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path); stability::early_report_deprecation( &mut self.lint_buffer, diff --git a/compiler/rustc_resolve/src/rustdoc.rs b/compiler/rustc_resolve/src/rustdoc.rs index fe4b8c7f69cb..f95c0acd7509 100644 --- a/compiler/rustc_resolve/src/rustdoc.rs +++ b/compiler/rustc_resolve/src/rustdoc.rs @@ -404,7 +404,7 @@ pub(crate) fn attrs_to_preprocessed_links(attrs: &[ast::Attribute]) -> Vec(doc: &'md str) -> Vec> { let mut broken_link_callback = |link: BrokenLink<'md>| Some((link.reference, "".into())); let mut event_iter = Parser::new_with_broken_link_callback( - &doc, + doc, main_body_opts(), Some(&mut broken_link_callback), ) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index d4f9122e7e38..8ab48c990074 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -857,7 +857,7 @@ impl OutFileName { pub fn as_path(&self) -> &Path { match *self { OutFileName::Real(ref path) => path.as_ref(), - OutFileName::Stdout => &Path::new("stdout"), + OutFileName::Stdout => Path::new("stdout"), } } diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 38e09f47eacd..efd75ce61518 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -808,7 +808,7 @@ impl Session { /// Returns a list of directories where target-specific tool binaries are located. pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec { - let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple()); + let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, config::host_triple()); let p = PathBuf::from_iter([ Path::new(&self.sysroot), Path::new(&rustlib_path), diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index 147d683b51f1..24b1a3c63be6 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -212,14 +212,14 @@ impl<'tcx> RustcInternal<'tcx> for BoundVariableKind { BoundVariableKind::Ty(kind) => rustc_ty::BoundVariableKind::Ty(match kind { BoundTyKind::Anon => rustc_ty::BoundTyKind::Anon, BoundTyKind::Param(def, symbol) => { - rustc_ty::BoundTyKind::Param(def.0.internal(tables), Symbol::intern(&symbol)) + rustc_ty::BoundTyKind::Param(def.0.internal(tables), Symbol::intern(symbol)) } }), BoundVariableKind::Region(kind) => rustc_ty::BoundVariableKind::Region(match kind { BoundRegionKind::BrAnon => rustc_ty::BoundRegionKind::BrAnon, BoundRegionKind::BrNamed(def, symbol) => rustc_ty::BoundRegionKind::BrNamed( def.0.internal(tables), - Symbol::intern(&symbol), + Symbol::intern(symbol), ), BoundRegionKind::BrEnv => rustc_ty::BoundRegionKind::BrEnv, }), diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index 1501e7d0cf75..1fd8542b2a64 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -552,7 +552,7 @@ fn encode_ty<'tcx>( // Use user-defined CFI encoding for type if let Some(value_str) = cfi_encoding.value_str() { if !value_str.to_string().trim().is_empty() { - s.push_str(&value_str.to_string().trim()); + s.push_str(value_str.to_string().trim()); } else { #[allow( rustc::diagnostic_outside_of_impl, @@ -604,7 +604,7 @@ fn encode_ty<'tcx>( // Use user-defined CFI encoding for type if let Some(value_str) = cfi_encoding.value_str() { if !value_str.to_string().trim().is_empty() { - s.push_str(&value_str.to_string().trim()); + s.push_str(value_str.to_string().trim()); } else { #[allow( rustc::diagnostic_outside_of_impl, @@ -1145,5 +1145,5 @@ pub fn typeid_for_instance<'tcx>( } } - typeid_for_fnabi(tcx, &fn_abi, options) + typeid_for_fnabi(tcx, fn_abi, options) } diff --git a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs index b6d2228d4b8f..59c979cf437f 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs @@ -97,7 +97,7 @@ pub(super) trait GoalKind<'tcx>: bug!("expected object type in `consider_object_bound_candidate`"); }; ecx.add_goals(structural_traits::predicates_for_object_candidate( - &ecx, + ecx, goal.param_env, goal.predicate.trait_ref(tcx), bounds, diff --git a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs index 6eefccbde04c..f442e2a08a81 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs @@ -50,14 +50,14 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_auto_trait<'tcx>( ty::Array(element_ty, _) | ty::Slice(element_ty) => Ok(vec![element_ty]), - ty::Tuple(ref tys) => { + ty::Tuple(tys) => { // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet Ok(tys.iter().collect()) } - ty::Closure(_, ref args) => Ok(vec![args.as_closure().tupled_upvars_ty()]), + ty::Closure(_, args) => Ok(vec![args.as_closure().tupled_upvars_ty()]), - ty::Coroutine(_, ref args, _) => { + ty::Coroutine(_, args, _) => { let coroutine_args = args.as_coroutine(); Ok(vec![coroutine_args.tupled_upvars_ty(), coroutine_args.witness()]) } diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 5752d49ed2cf..a287582dca7b 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -175,7 +175,7 @@ impl<'a, 'tcx> InspectGoal<'a, 'tcx> { warn!("unexpected root evaluation: {:?}", self.evaluation); return vec![]; } - inspect::CanonicalGoalEvaluationKind::Evaluation { ref revisions } => { + inspect::CanonicalGoalEvaluationKind::Evaluation { revisions } => { if let Some(last) = revisions.last() { last } else { diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index dbf6749b5237..79314b4dfb46 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -252,7 +252,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { fresh_preds.insert(self.clean_pred(infcx, predicate.as_predicate())); } - let mut select = SelectionContext::new(&infcx); + let mut select = SelectionContext::new(infcx); let mut already_visited = FxHashSet::default(); let mut predicates = VecDeque::new(); diff --git a/compiler/rustc_trait_selection/src/traits/engine.rs b/compiler/rustc_trait_selection/src/traits/engine.rs index d9a1a98191d0..67718d0a3484 100644 --- a/compiler/rustc_trait_selection/src/traits/engine.rs +++ b/compiler/rustc_trait_selection/src/traits/engine.rs @@ -108,7 +108,7 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> { param_env: ty::ParamEnv<'tcx>, value: T, ) -> T { - let infer_ok = self.infcx.at(&cause, param_env).normalize(value); + let infer_ok = self.infcx.at(cause, param_env).normalize(value); self.register_infer_ok_obligations(infer_ok) } @@ -204,7 +204,7 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> { generic_param_scope: LocalDefId, outlives_env: &OutlivesEnvironment<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let errors = self.infcx.resolve_regions(&outlives_env); + let errors = self.infcx.resolve_regions(outlives_env); if errors.is_empty() { Ok(()) } else { diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/infer_ctxt_ext.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/infer_ctxt_ext.rs index b4835b011ddb..0190d5ab4be0 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/infer_ctxt_ext.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/infer_ctxt_ext.rs @@ -61,8 +61,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { .params .iter() .map(|arg| { - if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } = - *arg.pat + if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat { Some(ArgKind::Tuple( Some(span), @@ -92,7 +91,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { .inputs .iter() .map(|arg| match arg.kind { - hir::TyKind::Tup(ref tys) => ArgKind::Tuple( + hir::TyKind::Tup(tys) => ArgKind::Tuple( Some(arg.span), vec![("_".to_owned(), "_".to_owned()); tys.len()], ), @@ -100,7 +99,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { }) .collect::>(), ), - Node::Ctor(ref variant_data) => { + Node::Ctor(variant_data) => { let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id)); (span, None, vec![ArgKind::empty(); variant_data.fields().len()]) } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index da2d5dfbfb5c..33e4fd33716f 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -482,7 +482,7 @@ impl<'tcx> OnUnimplementedDirective { match Self::parse( tcx, item_def_id, - &items, + items, item.span(), false, is_diagnostic_namespace_variant, @@ -875,7 +875,7 @@ impl<'tcx> OnUnimplementedFormatString { // don't break messages using these two arguments incorrectly &empty_string } else if s == sym::ItemContext { - &item_context + item_context } else if s == sym::integral { "{integral}" } else if s == sym::integer_ { 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 145b0cd0092f..38ef94a4d3bc 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -99,7 +99,7 @@ impl<'tcx, 'a> CoroutineData<'tcx, 'a> { .awaits .into_iter() .map(|id| hir.expect_expr(id)) - .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(&await_expr)))) + .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr)))) .map(|expr| expr.span) } } @@ -501,7 +501,7 @@ pub fn suggest_restriction<'tcx>( impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn suggest_restricting_param_bound( &self, - mut err: &mut Diagnostic, + err: &mut Diagnostic, trait_pred: ty::PolyTraitPredicate<'tcx>, associated_ty: Option<(&'static str, Ty<'tcx>)>, mut body_id: LocalDefId, @@ -533,7 +533,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { suggest_restriction( self.tcx, body_id, - &generics, + generics, "`Self`", err, None, @@ -552,7 +552,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { assert!(param_ty); // Restricting `Self` for a single method. suggest_restriction( - self.tcx, body_id, &generics, "`Self`", err, None, projection, trait_pred, + self.tcx, body_id, generics, "`Self`", err, None, projection, trait_pred, None, ); return; @@ -575,7 +575,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { suggest_restriction( self.tcx, body_id, - &generics, + generics, "the associated type", err, Some(fn_sig), @@ -595,7 +595,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { suggest_restriction( self.tcx, body_id, - &generics, + generics, "the associated type", err, None, @@ -662,7 +662,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if suggest_constraining_type_param( self.tcx, generics, - &mut err, + err, ¶m_name, &constraint, Some(trait_pred.def_id()), @@ -690,7 +690,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if suggest_arbitrary_trait_bound( self.tcx, generics, - &mut err, + err, trait_pred, associated_ty, ) { @@ -1273,7 +1273,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } = obligation.cause.code() { - &parent_code + parent_code } else if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code() { @@ -1867,7 +1867,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let body = self.tcx.hir().body(self.tcx.hir().body_owned_by(obligation.cause.body_id)); let mut visitor = ReturnsVisitor::default(); - visitor.visit_body(&body); + visitor.visit_body(body); let mut sugg = vec![(span.shrink_to_lo(), "Box<".to_string()), (span.shrink_to_hi(), ">".to_string())]; @@ -1922,7 +1922,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let body = hir.body(*body_id); // Point at all the `return`s in the function as they have failed trait bounds. let mut visitor = ReturnsVisitor::default(); - visitor.visit_body(&body); + visitor.visit_body(body); let typeck_results = self.typeck_results.as_ref().unwrap(); for expr in &visitor.returns { if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) { @@ -2300,7 +2300,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // cycles. If we can't use resolved types because the coroutine comes from another crate, // we still provide a targeted error but without all the relevant spans. let coroutine_data = match &self.typeck_results { - Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(&t), + Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t), _ if coroutine_did.is_local() => { CoroutineData(self.tcx.typeck(coroutine_did.expect_local())) } @@ -2344,7 +2344,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if interior_or_upvar_span.is_none() { interior_or_upvar_span = - coroutine_data.try_get_upvar_span(&self, coroutine_did, ty_matches); + coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches); } if interior_or_upvar_span.is_none() && !coroutine_did.is_local() { @@ -2517,7 +2517,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { CoroutineInteriorOrUpvar::Upvar(upvar_span) => { // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send` let non_send = match target_ty.kind() { - ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) { + ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) { Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())), _ => None, }, @@ -3305,7 +3305,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err, predicate, param_env, - &parent_code, + parent_code, obligated_types, seen_requirements, ) @@ -3660,9 +3660,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // If the expression we're calling on is a binding, we want to point at the // `let` when talking about the type. Otherwise we'll point at every part // of the method chain with the type. - self.point_at_chain(binding_expr, &typeck_results, type_diffs, param_env, err); + self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err); } else { - self.point_at_chain(expr, &typeck_results, type_diffs, param_env, err); + self.point_at_chain(expr, typeck_results, type_diffs, param_env, err); } } let call_node = hir.find(call_hir_id); @@ -3856,7 +3856,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { suggest_restriction( tcx, hir.body_owner_def_id(body_id), - &generics, + generics, &format!("type parameter `{ty}`"), err, node.fn_sig(), diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs index 5239725f5096..cdec07317781 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs @@ -511,7 +511,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if Some(trait_ref.def_id()) == tcx.lang_items().tuple_trait() { self.add_tuple_trait_message( - &obligation.cause.code().peel_derives(), + obligation.cause.code().peel_derives(), &mut err, ); } @@ -569,7 +569,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if Some(trait_ref.def_id()) == self.tcx.lang_items().sized_trait() { self.suggest_borrowing_for_object_cast( &mut err, - &root_obligation, + root_obligation, source, target, ); @@ -1965,7 +1965,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } } ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => { - self.get_parent_trait_ref(&parent_code) + self.get_parent_trait_ref(parent_code) } _ => None, } @@ -2180,7 +2180,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) { let mut expr_finder = FindExprBySpan::new(span); - expr_finder.visit_expr(&self.tcx.hir().body(body_id).value); + expr_finder.visit_expr(self.tcx.hir().body(body_id).value); if let Some(hir::Expr { kind: hir::ExprKind::Path(hir::QPath::Resolved(None, path)), @@ -2932,7 +2932,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { obligation.param_env, ) { self.report_similar_impl_candidates_for_root_obligation( - &obligation, + obligation, *trait_predicate, body_def_id, err, @@ -3044,13 +3044,13 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { (ty::ClosureKind::FnOnce, Some((span, place))) => { err.fn_once_label = Some(ClosureFnOnceLabel { span: *span, - place: ty::place_to_string_for_capture(self.tcx, &place), + place: ty::place_to_string_for_capture(self.tcx, place), }) } (ty::ClosureKind::FnMut, Some((span, place))) => { err.fn_mut_label = Some(ClosureFnMutLabel { span: *span, - place: ty::place_to_string_for_capture(self.tcx, &place), + place: ty::place_to_string_for_capture(self.tcx, place), }) } _ => {} @@ -3162,7 +3162,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let mut not_tupled = false; let found = match found_trait_ref.skip_binder().args.type_at(1).kind() { - ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()], + ty::Tuple(tys) => vec![ArgKind::empty(); tys.len()], _ => { not_tupled = true; vec![ArgKind::empty()] @@ -3171,7 +3171,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let expected_ty = expected_trait_ref.skip_binder().args.type_at(1); let expected = match expected_ty.kind() { - ty::Tuple(ref tys) => { + ty::Tuple(tys) => { tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect() } _ => { diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 3e5dd8c50d4a..5d5440094fdd 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -84,7 +84,7 @@ fn check_is_object_safe(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool { span, ) = violation { - lint_object_unsafe_trait(tcx, *span, trait_def_id, &violation); + lint_object_unsafe_trait(tcx, *span, trait_def_id, violation); } } return true; diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 3bc401128b3a..06f65e414da7 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -584,7 +584,7 @@ impl<'a, 'b, 'tcx> TypeFolder> for AssocTypeNormalizer<'a, 'b, 'tcx data, self.cause.clone(), self.depth, - &mut self.obligations, + self.obligations, ) } else { opt_normalize_projection_type( @@ -593,7 +593,7 @@ impl<'a, 'b, 'tcx> TypeFolder> for AssocTypeNormalizer<'a, 'b, 'tcx data, self.cause.clone(), self.depth, - &mut self.obligations, + self.obligations, ) .ok() .flatten() @@ -632,7 +632,7 @@ impl<'a, 'b, 'tcx> TypeFolder> for AssocTypeNormalizer<'a, 'b, 'tcx data, self.cause.clone(), self.depth, - &mut self.obligations, + self.obligations, ) .ok() .flatten() @@ -717,7 +717,7 @@ impl<'a, 'b, 'tcx> TypeFolder> for AssocTypeNormalizer<'a, 'b, 'tcx data, self.cause.clone(), self.depth, - &mut self.obligations, + self.obligations, ) } @@ -732,7 +732,7 @@ impl<'a, 'b, 'tcx> TypeFolder> for AssocTypeNormalizer<'a, 'b, 'tcx data, self.cause.clone(), self.depth, - &mut self.obligations, + self.obligations, ); PlaceholderReplacer::replace_placeholders( diff --git a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs index f8efa6a1f6c4..06d41243e75b 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -48,9 +48,7 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { // (T1..Tn) and closures have same properties as T1..Tn -- // check if *all* of them are trivial. ty::Tuple(tys) => tys.iter().all(|t| trivial_dropck_outlives(tcx, t)), - ty::Closure(_, ref args) => { - trivial_dropck_outlives(tcx, args.as_closure().tupled_upvars_ty()) - } + ty::Closure(_, args) => trivial_dropck_outlives(tcx, args.as_closure().tupled_upvars_ty()), ty::Adt(def, _) => { if Some(def.did()) == tcx.lang_items().manually_drop() { diff --git a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs index 65f32b1c48a4..04b3119323fa 100644 --- a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs +++ b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs @@ -108,7 +108,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { match self.evaluate_obligation(obligation) { Ok(result) => result, Err(OverflowError::Canonical) => { - let mut selcx = SelectionContext::new(&self); + let mut selcx = SelectionContext::new(self); selcx.evaluate_root_obligation(obligation).unwrap_or_else(|r| match r { OverflowError::Canonical => { span_bug!( diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 1529f736109a..307a36761f28 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -634,7 +634,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let self_ty = placeholder_trait_predicate.self_ty(); let principal_trait_ref = match self_ty.kind() { - ty::Dynamic(ref data, ..) => { + ty::Dynamic(data, ..) => { if data.auto_traits().any(|did| did == obligation.predicate.def_id()) { debug!( "assemble_candidates_from_object_ty: matched builtin bound, \ @@ -759,10 +759,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { match (source.kind(), target.kind()) { // Trait+Kx+'a -> Trait+Ky+'b (upcasts). - ( - &ty::Dynamic(ref a_data, a_region, ty::Dyn), - &ty::Dynamic(ref b_data, b_region, ty::Dyn), - ) => { + (&ty::Dynamic(a_data, a_region, ty::Dyn), &ty::Dynamic(b_data, b_region, ty::Dyn)) => { // Upcast coercions permit several things: // // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo` diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 2ab3ecbd5a3e..53b8b50252f3 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -394,7 +394,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligation.recursion_depth + 1, obligation.param_env, trait_def_id, - &trait_ref.args, + trait_ref.args, obligation.predicate, ); @@ -455,7 +455,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { recursion_depth, param_env, impl_def_id, - &args.value, + args.value, parent_trait_pred, ); @@ -708,7 +708,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligation.recursion_depth, obligation.param_env, trait_def_id, - &args, + args, obligation.predicate, ); @@ -986,7 +986,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { Ok(match (source.kind(), target.kind()) { // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping). - (&ty::Dynamic(ref data_a, r_a, dyn_a), &ty::Dynamic(ref data_b, r_b, dyn_b)) + (&ty::Dynamic(data_a, r_a, dyn_a), &ty::Dynamic(data_b, r_b, dyn_b)) if dyn_a == dyn_b => { // See `assemble_candidates_for_unsizing` for more info. @@ -1031,7 +1031,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } // `T` -> `Trait` - (_, &ty::Dynamic(ref data, r, ty::Dyn)) => { + (_, &ty::Dynamic(data, r, ty::Dyn)) => { let mut object_dids = data.auto_traits().chain(data.principal_def_id()); if let Some(did) = object_dids.find(|did| !tcx.check_is_object_safe(*did)) { return Err(TraitNotObjectSafe(did)); diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 1ed0da59b64f..32e8d5b10ec9 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -367,7 +367,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { debug_assert!(!self.infcx.next_trait_solver()); // Watch out for overflow. This intentionally bypasses (and does // not update) the cache. - self.check_recursion_limit(&stack.obligation, &stack.obligation)?; + self.check_recursion_limit(stack.obligation, stack.obligation)?; // Check the cache. Note that we freshen the trait-ref // separately rather than using `stack.fresh_trait_ref` -- @@ -416,7 +416,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let mut no_candidates_apply = true; for c in candidate_set.vec.iter() { - if self.evaluate_candidate(stack, &c)?.may_apply() { + if self.evaluate_candidate(stack, c)?.may_apply() { no_candidates_apply = false; break; } @@ -2218,7 +2218,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } } - ty::CoroutineWitness(def_id, ref args) => { + ty::CoroutineWitness(def_id, args) => { let hidden_types = bind_coroutine_hidden_types_above( self.infcx, def_id, @@ -2307,23 +2307,23 @@ impl<'tcx> SelectionContext<'_, 'tcx> { ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]), - ty::Tuple(ref tys) => { + ty::Tuple(tys) => { // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet t.rebind(tys.iter().collect()) } - ty::Closure(_, ref args) => { + ty::Closure(_, args) => { let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty()); t.rebind(vec![ty]) } - ty::Coroutine(_, ref args, _) => { + ty::Coroutine(_, args, _) => { let ty = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty()); let witness = args.as_coroutine().witness(); t.rebind([ty].into_iter().chain(iter::once(witness)).collect()) } - ty::CoroutineWitness(def_id, ref args) => { + ty::CoroutineWitness(def_id, args) => { bind_coroutine_hidden_types_above(self.infcx, def_id, args, t.bound_vars()) } diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index efab29743f4e..0f7a0ab17ef1 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -107,7 +107,7 @@ pub fn translate_args_with_cause<'tcx>( param_env, source_impl, source_args, target_node ); let source_trait_ref = - infcx.tcx.impl_trait_ref(source_impl).unwrap().instantiate(infcx.tcx, &source_args); + infcx.tcx.impl_trait_ref(source_impl).unwrap().instantiate(infcx.tcx, source_args); // translate the Self and Param parts of the substitution, since those // vary across impls @@ -197,25 +197,22 @@ fn fulfill_implication<'tcx>( param_env, source_trait_ref, target_impl ); - let source_trait_ref = match traits::fully_normalize( - &infcx, - ObligationCause::dummy(), - param_env, - source_trait_ref, - ) { - Ok(source_trait_ref) => source_trait_ref, - Err(_errors) => { - infcx.tcx.sess.delay_span_bug( - infcx.tcx.def_span(source_impl), - format!("failed to fully normalize {source_trait_ref}"), - ); - source_trait_ref - } - }; + let source_trait_ref = + match traits::fully_normalize(infcx, ObligationCause::dummy(), param_env, source_trait_ref) + { + Ok(source_trait_ref) => source_trait_ref, + Err(_errors) => { + infcx.tcx.sess.delay_span_bug( + infcx.tcx.def_span(source_impl), + format!("failed to fully normalize {source_trait_ref}"), + ); + source_trait_ref + } + }; let source_trait = ImplSubject::Trait(source_trait_ref); - let selcx = &mut SelectionContext::new(&infcx); + let selcx = &mut SelectionContext::new(infcx); let target_args = infcx.fresh_args_for_item(DUMMY_SP, target_impl); let (target_trait, obligations) = util::impl_subject_and_oblig(selcx, param_env, target_impl, target_args, error_cause); diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 9751cb60ed89..3a890d70d79b 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -624,7 +624,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // Note that we handle the len is implicitly checked while walking `arg`. } - ty::Tuple(ref tys) => { + ty::Tuple(tys) => { if let Some((_last, rest)) = tys.split_last() { for &elem in rest { self.require_sized(elem, traits::TupleElem); diff --git a/compiler/rustc_traits/src/evaluate_obligation.rs b/compiler/rustc_traits/src/evaluate_obligation.rs index 9fd550495aad..ce22da23fffd 100644 --- a/compiler/rustc_traits/src/evaluate_obligation.rs +++ b/compiler/rustc_traits/src/evaluate_obligation.rs @@ -22,7 +22,7 @@ fn evaluate_obligation<'tcx>( debug!("evaluate_obligation: goal={:#?}", goal); let ParamEnvAnd { param_env, value: predicate } = goal; - let mut selcx = SelectionContext::with_query_mode(&infcx, TraitQueryMode::Canonical); + let mut selcx = SelectionContext::with_query_mode(infcx, TraitQueryMode::Canonical); let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate); selcx.evaluate_root_obligation(&obligation) diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index 0a34aef16ae0..e29fed37f85b 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -23,7 +23,7 @@ pub(crate) fn provide(providers: &mut Providers) { fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] { let item = tcx.hir().expect_item(def_id); match item.kind { - hir::ItemKind::Trait(.., ref trait_item_refs) => { + hir::ItemKind::Trait(.., trait_item_refs) => { // We collect RPITITs for each trait method's return type and create a // corresponding associated item using associated_types_for_impl_traits_in_associated_fn // query. @@ -47,7 +47,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] { ), ) } - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl(impl_) => { // We collect RPITITs for each trait method's return type, on the impl side too and // create a corresponding associated item using // associated_types_for_impl_traits_in_associated_fn query. @@ -98,7 +98,7 @@ fn associated_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AssocItem { let parent_def_id = tcx.hir().get_parent_item(id); let parent_item = tcx.hir().expect_item(parent_def_id.def_id); match parent_item.kind { - hir::ItemKind::Impl(ref impl_) => { + hir::ItemKind::Impl(impl_) => { if let Some(impl_item_ref) = impl_.items.iter().find(|i| i.id.owner_id.def_id == def_id) { let assoc_item = associated_item_from_impl_item_ref(impl_item_ref); @@ -107,7 +107,7 @@ fn associated_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AssocItem { } } - hir::ItemKind::Trait(.., ref trait_item_refs) => { + hir::ItemKind::Trait(.., trait_item_refs) => { if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.owner_id.def_id == def_id) { diff --git a/compiler/rustc_ty_utils/src/consts.rs b/compiler/rustc_ty_utils/src/consts.rs index 9ced50c8e138..b521a5c1145f 100644 --- a/compiler/rustc_ty_utils/src/consts.rs +++ b/compiler/rustc_ty_utils/src/consts.rs @@ -375,7 +375,7 @@ impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> { impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> { fn thir(&self) -> &'a thir::Thir<'tcx> { - &self.thir + self.thir } #[instrument(skip(self), level = "debug")] diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index b09566e16682..826c69ee7160 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -320,7 +320,7 @@ fn layout_of_uncached<'tcx>( ty::Coroutine(def_id, args, _) => coroutine_layout(cx, ty, def_id, args)?, - ty::Closure(_, ref args) => { + ty::Closure(_, args) => { let tys = args.as_closure().upvar_tys(); univariant( &tys.iter() @@ -728,7 +728,7 @@ fn coroutine_layout<'tcx>( let Some(info) = tcx.coroutine_layout(def_id) else { return Err(error(cx, LayoutError::Unknown(ty))); }; - let (ineligible_locals, assignments) = coroutine_saved_local_eligibility(&info); + let (ineligible_locals, assignments) = coroutine_saved_local_eligibility(info); // Build a prefix layout, including "promoting" all ineligible // locals as part of the prefix. We compute the layout of all of diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index b7c75da7301f..56e84b6015d4 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -25,7 +25,7 @@ fn sized_constraint_for_ty<'tcx>( vec![ty] } - Tuple(ref tys) => match tys.last() { + Tuple(tys) => match tys.last() { None => vec![], Some(&ty) => sized_constraint_for_ty(tcx, adtdef, ty), }, @@ -285,7 +285,7 @@ fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option data.principal().is_none(), + ty::Dynamic(data, re, _) if re.is_static() => data.principal().is_none(), _ => false, }; diff --git a/compiler/stable_mir/src/mir/pretty.rs b/compiler/stable_mir/src/mir/pretty.rs index e52c3360ce42..c7422d66c0e8 100644 --- a/compiler/stable_mir/src/mir/pretty.rs +++ b/compiler/stable_mir/src/mir/pretty.rs @@ -93,7 +93,7 @@ pub fn pretty_rvalue(rval: &Rvalue) -> String { match rval { Rvalue::AddressOf(muta, addr) => { pretty.push_str("&raw "); - pretty.push_str(&ret_mutability(&muta)); + pretty.push_str(&ret_mutability(muta)); pretty.push_str(format!("(*_{})", addr.local).as_str()); } Rvalue::Aggregate(aggregatekind, operands) => { @@ -155,7 +155,7 @@ pub fn pretty_rvalue(rval: &Rvalue) -> String { } Rvalue::NullaryOp(nul, ty) => { pretty.push_str(format!("{:#?}", nul).as_str()); - pretty.push_str(&&pretty_ty(ty.kind())); + pretty.push_str(&pretty_ty(ty.kind())); pretty.push_str(" "); } Rvalue::UnaryOp(un, op) => { diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs index 40bedd67352f..bc2d57eaa24e 100644 --- a/compiler/stable_mir/src/mir/visit.rs +++ b/compiler/stable_mir/src/mir/visit.rs @@ -224,7 +224,7 @@ pub trait MirVisitor { fn super_terminator(&mut self, term: &Terminator, location: Location) { let Terminator { kind, span } = term; - self.visit_span(&span); + self.visit_span(span); match kind { TerminatorKind::Goto { .. } | TerminatorKind::Resume diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index f0b11dce9aac..abe6f8ec12f1 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -138,7 +138,7 @@ impl Span { /// Return lines that corespond to this `Span` pub fn get_lines(&self) -> LineInfo { - with(|c| c.get_lines(&self)) + with(|c| c.get_lines(self)) } } From d82a08537aab25f3d1d43a30ea4b06422819bbfd Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 20 Nov 2023 13:15:47 -0700 Subject: [PATCH 18/66] rustdoc-search: clean up `checkPath` This computes the same result with less code by computing many of the old checks at once: * It won't enter the loop if clength > length, because then the result of length - clength will be negative and the loop conditional will fail. * i + clength will never be greater than length, because it starts out as i = length - clength, implying that i + clength equals length, and it only goes down from there. * The aborted variable is replaced with control flow. --- src/librustdoc/html/static/js/search.js | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 22dcb8701431..495c28d91e8a 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -1840,26 +1840,16 @@ function initSearch(rawSearchIndex) { const length = path.length; const clength = contains.length; - if (clength > length) { - return maxEditDistance + 1; - } - for (let i = 0; i < length; ++i) { - if (i + clength > length) { - break; - } + pathiter: for (let i = length - clength; i >= 0; i -= 1) { let dist_total = 0; - let aborted = false; for (let x = 0; x < clength; ++x) { const dist = editDistance(path[i + x], contains[x], maxEditDistance); if (dist > maxEditDistance) { - aborted = true; - break; + continue pathiter; } dist_total += dist; } - if (!aborted) { - ret_dist = Math.min(ret_dist, Math.round(dist_total / clength)); - } + ret_dist = Math.min(ret_dist, Math.round(dist_total / clength)); } return ret_dist; } From 28f17d97a9e7276a383e11e91ef2d4159e670726 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 20 Nov 2023 13:37:57 -0700 Subject: [PATCH 19/66] rustdoc-search: make primitives and keywords less special The search sorting code already sorts by item type discriminant, putting things with smaller discriminants first. There was also a special case for sorting keywords and primitives earlier, and this commit removes it by giving them lower discriminants. The sorting code has another criteria where items with descriptions appear earlier than items without, and that criteria has higher priority than the item type. This shouldn't matter, though, because primitives and keywords normally only appear in the standard library, and it always gives them descriptions. --- src/librustdoc/formats/item_type.rs | 51 ++++++++++++---------- src/librustdoc/html/static/js/search.js | 36 +++++---------- tests/rustdoc-js-std/keyword.js | 4 +- tests/rustdoc-js-std/macro-check.js | 4 +- tests/rustdoc-js-std/parser-bindings.js | 8 ++-- tests/rustdoc-js-std/parser-filter.js | 22 +++++----- tests/rustdoc-js-std/parser-ident.js | 6 +-- tests/rustdoc-js-std/parser-returned.js | 2 +- tests/rustdoc-js-std/parser-slice-array.js | 20 ++++----- 9 files changed, 74 insertions(+), 79 deletions(-) diff --git a/src/librustdoc/formats/item_type.rs b/src/librustdoc/formats/item_type.rs index 22527876b76f..5666751d1ce9 100644 --- a/src/librustdoc/formats/item_type.rs +++ b/src/librustdoc/formats/item_type.rs @@ -16,6 +16,13 @@ use crate::clean; /// Consequently, every change to this type should be synchronized to /// the `itemTypes` mapping table in `html/static/js/search.js`. /// +/// The search engine in search.js also uses item type numbers as a tie breaker when +/// sorting results. Keywords and primitives are given first because we want them to be easily +/// found by new users who don't know about advanced features like type filters. The rest are +/// mostly in an arbitrary order, but it's easier to test the search engine when +/// it's deterministic, and these are strictly finer-grained than language namespaces, so +/// using the path and the item type together to sort ensures that search sorting is stable. +/// /// In addition, code in `html::render` uses this enum to generate CSS classes, page prefixes, and /// module headings. If you are adding to this enum and want to ensure that the sidebar also prints /// a heading, edit the listing in `html/render.rs`, function `sidebar_module`. This uses an @@ -23,28 +30,28 @@ use crate::clean; #[derive(Copy, PartialEq, Eq, Hash, Clone, Debug, PartialOrd, Ord)] #[repr(u8)] pub(crate) enum ItemType { - Module = 0, - ExternCrate = 1, - Import = 2, - Struct = 3, - Enum = 4, - Function = 5, - TypeAlias = 6, - Static = 7, - Trait = 8, - Impl = 9, - TyMethod = 10, - Method = 11, - StructField = 12, - Variant = 13, - Macro = 14, - Primitive = 15, - AssocType = 16, - Constant = 17, - AssocConst = 18, - Union = 19, - ForeignType = 20, - Keyword = 21, + Keyword = 0, + Primitive = 1, + Module = 2, + ExternCrate = 3, + Import = 4, + Struct = 5, + Enum = 6, + Function = 7, + TypeAlias = 8, + Static = 9, + Trait = 10, + Impl = 11, + TyMethod = 12, + Method = 13, + StructField = 14, + Variant = 15, + Macro = 16, + AssocType = 17, + Constant = 18, + AssocConst = 19, + Union = 20, + ForeignType = 21, OpaqueTy = 22, ProcAttribute = 23, ProcDerive = 24, diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 495c28d91e8a..4822690fd04b 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -18,28 +18,28 @@ if (!Array.prototype.toSpliced) { // This mapping table should match the discriminants of // `rustdoc::formats::item_type::ItemType` type in Rust. const itemTypes = [ + "keyword", + "primitive", "mod", "externcrate", "import", - "struct", + "struct", // 5 "enum", - "fn", // 5 + "fn", "type", "static", - "trait", + "trait", // 10 "impl", - "tymethod", // 10 + "tymethod", "method", "structfield", - "variant", + "variant", // 15 "macro", - "primitive", // 15 "associatedtype", "constant", "associatedconstant", - "union", - "foreigntype", // 20 - "keyword", + "union", // 20 + "foreigntype", "existential", "attr", "derive", @@ -48,6 +48,8 @@ const itemTypes = [ ]; const longItemTypes = [ + "keyword", + "primitive type", "module", "extern crate", "re-export", @@ -63,13 +65,11 @@ const longItemTypes = [ "struct field", "enum variant", "macro", - "primitive type", "assoc type", "constant", "assoc const", "union", "foreign type", - "keyword", "existential type", "attribute macro", "derive macro", @@ -77,8 +77,6 @@ const longItemTypes = [ ]; // used for special search precedence -const TY_PRIMITIVE = itemTypes.indexOf("primitive"); -const TY_KEYWORD = itemTypes.indexOf("keyword"); const TY_GENERIC = itemTypes.indexOf("generic"); const ROOT_PATH = typeof window !== "undefined" ? window.rootPath : "../"; @@ -1317,16 +1315,6 @@ function initSearch(rawSearchIndex) { return (a > b ? +1 : -1); } - // special precedence for primitive and keyword pages - if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) || - (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) { - return -1; - } - if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) || - (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) { - return 1; - } - // sort by description (no description goes later) a = (aaa.item.desc === ""); b = (bbb.item.desc === ""); @@ -2943,7 +2931,7 @@ ${item.displayPath}${name}\ // https://mathiasbynens.be/notes/shapes-ics const crateRow = { crate: crate, - ty: 1, // == ExternCrate + ty: 3, // == ExternCrate name: crate, path: "", desc: crateCorpus.doc, diff --git a/tests/rustdoc-js-std/keyword.js b/tests/rustdoc-js-std/keyword.js index b85ba34138ba..1837b1e71f78 100644 --- a/tests/rustdoc-js-std/keyword.js +++ b/tests/rustdoc-js-std/keyword.js @@ -3,7 +3,7 @@ const EXPECTED = { 'query': 'fn', 'others': [ - { 'path': 'std', 'name': 'fn', ty: 15 }, // 15 is for primitive types - { 'path': 'std', 'name': 'fn', ty: 21 }, // 21 is for keywords + { 'path': 'std', 'name': 'fn', ty: 1 }, // 1 is for primitive types + { 'path': 'std', 'name': 'fn', ty: 0 }, // 0 is for keywords ], }; diff --git a/tests/rustdoc-js-std/macro-check.js b/tests/rustdoc-js-std/macro-check.js index c22b1753fd71..37d5e7dae62e 100644 --- a/tests/rustdoc-js-std/macro-check.js +++ b/tests/rustdoc-js-std/macro-check.js @@ -3,7 +3,7 @@ const EXPECTED = { 'query': 'panic', 'others': [ - { 'path': 'std', 'name': 'panic', ty: 14 }, // 15 is for macros - { 'path': 'std', 'name': 'panic', ty: 0 }, // 0 is for modules + { 'path': 'std', 'name': 'panic', ty: 16 }, // 16 is for macros + { 'path': 'std', 'name': 'panic', ty: 2 }, // 2 is for modules ], }; diff --git a/tests/rustdoc-js-std/parser-bindings.js b/tests/rustdoc-js-std/parser-bindings.js index faf880c8116c..c4909c6242d7 100644 --- a/tests/rustdoc-js-std/parser-bindings.js +++ b/tests/rustdoc-js-std/parser-bindings.js @@ -81,7 +81,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }] ], ], @@ -112,7 +112,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }] ], ], @@ -149,10 +149,10 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }] ], ], diff --git a/tests/rustdoc-js-std/parser-filter.js b/tests/rustdoc-js-std/parser-filter.js index 3b9cc5b1bf09..a1dd0ea3b5a9 100644 --- a/tests/rustdoc-js-std/parser-filter.js +++ b/tests/rustdoc-js-std/parser-filter.js @@ -7,7 +7,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "foo", generics: [], - typeFilter: 5, + typeFilter: 7, }], foundElems: 1, original: "fn:foo", @@ -23,7 +23,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "foo", generics: [], - typeFilter: 4, + typeFilter: 6, }], foundElems: 1, original: "enum : foo", @@ -48,7 +48,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "macro", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "macro!", @@ -64,7 +64,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "mac", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "macro:mac!", @@ -80,7 +80,7 @@ const PARSED = [ pathWithoutLast: ["a"], pathLast: "mac", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "a::mac!", @@ -99,7 +99,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "foo", generics: [], - typeFilter: 5, + typeFilter: 7, }], userQuery: "-> fn:foo", error: null, @@ -121,10 +121,10 @@ const PARSED = [ pathWithoutLast: [], pathLast: "bar", generics: [], - typeFilter: 5, + typeFilter: 7, } ], - typeFilter: 5, + typeFilter: 7, }], userQuery: "-> fn:foo", error: null, @@ -146,7 +146,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "bar", generics: [], - typeFilter: 5, + typeFilter: 7, }, { name: "baz::fuzz", @@ -154,10 +154,10 @@ const PARSED = [ pathWithoutLast: ["baz"], pathLast: "fuzz", generics: [], - typeFilter: 4, + typeFilter: 6, }, ], - typeFilter: 5, + typeFilter: 7, }], userQuery: "-> fn:foo", error: null, diff --git a/tests/rustdoc-js-std/parser-ident.js b/tests/rustdoc-js-std/parser-ident.js index f65a7ce6692b..cc79c58f1da3 100644 --- a/tests/rustdoc-js-std/parser-ident.js +++ b/tests/rustdoc-js-std/parser-ident.js @@ -13,7 +13,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], typeFilter: -1, @@ -32,7 +32,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }], foundElems: 1, original: "!", @@ -48,7 +48,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "a", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "a!", diff --git a/tests/rustdoc-js-std/parser-returned.js b/tests/rustdoc-js-std/parser-returned.js index 6ea86609115b..44e517c49b59 100644 --- a/tests/rustdoc-js-std/parser-returned.js +++ b/tests/rustdoc-js-std/parser-returned.js @@ -89,7 +89,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }], userQuery: "-> !", error: null, diff --git a/tests/rustdoc-js-std/parser-slice-array.js b/tests/rustdoc-js-std/parser-slice-array.js index c22b7870dbf8..239391bed420 100644 --- a/tests/rustdoc-js-std/parser-slice-array.js +++ b/tests/rustdoc-js-std/parser-slice-array.js @@ -43,16 +43,16 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -70,7 +70,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }, { name: "u8", @@ -105,7 +105,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -140,7 +140,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -176,7 +176,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -194,7 +194,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -284,7 +284,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, From c089a162d80dbbcc0543649fa78ccabac569db81 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Tue, 21 Nov 2023 21:46:17 +0100 Subject: [PATCH 20/66] Fix some unnecessary casts `x clippy compiler -Aclippy::all -Wclippy::unnecessary_cast --fix` with some manual review to ensure every fix is correct. --- compiler/rustc_codegen_ssa/src/mir/place.rs | 12 +++++------- compiler/rustc_const_eval/src/const_eval/machine.rs | 2 +- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- compiler/rustc_infer/src/infer/fudge.rs | 4 ++-- .../src/infer/lexical_region_resolve/mod.rs | 12 ++++-------- .../rustc_infer/src/infer/region_constraints/mod.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 6 +----- compiler/rustc_metadata/src/rmeta/table.rs | 2 +- compiler/rustc_middle/src/mir/tcx.rs | 4 +--- compiler/rustc_symbol_mangling/src/v0.rs | 2 +- 10 files changed, 18 insertions(+), 30 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index eb590a45a63f..45795a7f7359 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -474,27 +474,25 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { cg_base.project_index(bx, llindex) } mir::ProjectionElem::ConstantIndex { offset, from_end: false, min_length: _ } => { - let lloffset = bx.cx().const_usize(offset as u64); + let lloffset = bx.cx().const_usize(offset); cg_base.project_index(bx, lloffset) } mir::ProjectionElem::ConstantIndex { offset, from_end: true, min_length: _ } => { - let lloffset = bx.cx().const_usize(offset as u64); + let lloffset = bx.cx().const_usize(offset); let lllen = cg_base.len(bx.cx()); let llindex = bx.sub(lllen, lloffset); cg_base.project_index(bx, llindex) } mir::ProjectionElem::Subslice { from, to, from_end } => { - let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from as u64)); + let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from)); let projected_ty = PlaceTy::from_ty(cg_base.layout.ty).projection_ty(tcx, *elem).ty; subslice.layout = bx.cx().layout_of(self.monomorphize(projected_ty)); if subslice.layout.is_unsized() { assert!(from_end, "slice subslices should be `from_end`"); - subslice.llextra = Some(bx.sub( - cg_base.llextra.unwrap(), - bx.cx().const_usize((from as u64) + (to as u64)), - )); + subslice.llextra = + Some(bx.sub(cg_base.llextra.unwrap(), bx.cx().const_usize(from + to))); } subslice diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 4b447229c5f6..5b04b37cdf51 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -485,7 +485,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, }; let ptr = ecx.allocate_ptr( - Size::from_bytes(size as u64), + Size::from_bytes(size), align, interpret::MemoryKind::Machine(MemoryKind::Heap), )?; diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index d2a72f8f2338..22d94b9ca281 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1861,7 +1861,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // method yet. So create fresh variables here for those too, // if there are any. let generics = self.tcx.generics_of(method); - assert_eq!(args.len(), generics.parent_count as usize); + assert_eq!(args.len(), generics.parent_count); let xform_fn_sig = if generics.params.is_empty() { fn_sig.instantiate(self.tcx, args) diff --git a/compiler/rustc_infer/src/infer/fudge.rs b/compiler/rustc_infer/src/infer/fudge.rs index 7e878ac06c7f..8ca97ae1b8e5 100644 --- a/compiler/rustc_infer/src/infer/fudge.rs +++ b/compiler/rustc_infer/src/infer/fudge.rs @@ -187,7 +187,7 @@ impl<'a, 'tcx> TypeFolder> for InferenceFudger<'a, 'tcx> { if self.type_vars.0.contains(&vid) { // This variable was created during the fudging. // Recreate it with a fresh variable here. - let idx = (vid.as_usize() - self.type_vars.0.start.as_usize()) as usize; + let idx = vid.as_usize() - self.type_vars.0.start.as_usize(); let origin = self.type_vars.1[idx]; self.infcx.next_ty_var(origin) } else { @@ -236,7 +236,7 @@ impl<'a, 'tcx> TypeFolder> for InferenceFudger<'a, 'tcx> { if self.const_vars.0.contains(&vid) { // This variable was created during the fudging. // Recreate it with a fresh variable here. - let idx = (vid.index() - self.const_vars.0.start.index()) as usize; + let idx = vid.index() - self.const_vars.0.start.index(); let origin = self.const_vars.1[idx]; self.infcx.next_const_var(ct.ty(), origin) } else { diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index 800aee1f4d3b..b0e82a92674f 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -681,17 +681,13 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { for constraint in self.data.constraints.keys() { match *constraint { Constraint::VarSubVar(a_id, b_id) => { - graph.add_edge( - NodeIndex(a_id.index() as usize), - NodeIndex(b_id.index() as usize), - *constraint, - ); + graph.add_edge(NodeIndex(a_id.index()), NodeIndex(b_id.index()), *constraint); } Constraint::RegSubVar(_, b_id) => { - graph.add_edge(dummy_source, NodeIndex(b_id.index() as usize), *constraint); + graph.add_edge(dummy_source, NodeIndex(b_id.index()), *constraint); } Constraint::VarSubReg(a_id, _) => { - graph.add_edge(NodeIndex(a_id.index() as usize), dummy_sink, *constraint); + graph.add_edge(NodeIndex(a_id.index()), dummy_sink, *constraint); } Constraint::RegSubReg(..) => { // this would be an edge from `dummy_source` to @@ -878,7 +874,7 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { ) { debug!("process_edges(source_vid={:?}, dir={:?})", source_vid, dir); - let source_node_index = NodeIndex(source_vid.index() as usize); + let source_node_index = NodeIndex(source_vid.index()); for (_, edge) in graph.adjacent_edges(source_node_index, dir) { match edge.data { Constraint::VarSubVar(from_vid, to_vid) => { diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index e888340bde3f..260f4bc671fb 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -316,7 +316,7 @@ impl<'tcx> RegionConstraintStorage<'tcx> { match undo_entry { AddVar(vid) => { self.var_infos.pop().unwrap(); - assert_eq!(self.var_infos.len(), vid.index() as usize); + assert_eq!(self.var_infos.len(), vid.index()); } AddConstraint(ref constraint) => { self.data.constraints.remove(constraint); diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index b6ffdc7378f6..109757f8719c 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -2269,11 +2269,7 @@ fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) { file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap(); // Record metadata size for self-profiling - tcx.prof.artifact_size( - "crate_metadata", - "crate_metadata", - file.metadata().unwrap().len() as u64, - ); + tcx.prof.artifact_size("crate_metadata", "crate_metadata", file.metadata().unwrap().len()); } pub fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index 027994c40ab7..0d97b6b76744 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -497,7 +497,7 @@ impl> TableBui } LazyTable::from_position_and_encoded_size( - NonZeroUsize::new(pos as usize).unwrap(), + NonZeroUsize::new(pos).unwrap(), width, self.blocks.len(), ) diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index 6ab2da23a8ad..17eb6ae274e1 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -95,9 +95,7 @@ impl<'tcx> PlaceTy<'tcx> { ProjectionElem::Subslice { from, to, from_end } => { PlaceTy::from_ty(match self.ty.kind() { ty::Slice(..) => self.ty, - ty::Array(inner, _) if !from_end => { - Ty::new_array(tcx, *inner, (to - from) as u64) - } + ty::Array(inner, _) if !from_end => Ty::new_array(tcx, *inner, to - from), ty::Array(inner, size) if from_end => { let size = size.eval_target_usize(tcx, param_env); let len = size - from - to; diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 01cbee3a7159..88989806997e 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -189,7 +189,7 @@ impl<'tcx> SymbolMangler<'tcx> { self.push("N"); self.out.push(ns); print_prefix(self)?; - self.push_disambiguator(disambiguator as u64); + self.push_disambiguator(disambiguator); self.push_ident(name); Ok(()) } From 2f51f0b2900db805f8230da07d45f4033cc29ecb Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 09:01:24 +1100 Subject: [PATCH 21/66] Remove unneeded features. --- compiler/rustc_ast_pretty/src/lib.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/lib.rs b/compiler/rustc_ast_pretty/src/lib.rs index 9e4ffd8dd6a3..670f2a458358 100644 --- a/compiler/rustc_ast_pretty/src/lib.rs +++ b/compiler/rustc_ast_pretty/src/lib.rs @@ -3,9 +3,7 @@ #![doc(rust_logo)] #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] -#![feature(associated_type_bounds)] #![feature(box_patterns)] -#![feature(with_negative_coherence)] #![recursion_limit = "256"] mod helpers; From 1d320ed38708f2a1c72553d3d42e1ccb6b79373b Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 09:15:19 +1100 Subject: [PATCH 22/66] Remove unnecessary derives. --- compiler/rustc_ast_pretty/src/pp.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pp.rs b/compiler/rustc_ast_pretty/src/pp.rs index 7ab8c3eaba22..249d02a76da3 100644 --- a/compiler/rustc_ast_pretty/src/pp.rs +++ b/compiler/rustc_ast_pretty/src/pp.rs @@ -177,7 +177,7 @@ pub struct BeginToken { breaks: Breaks, } -#[derive(Clone, PartialEq)] +#[derive(PartialEq)] pub enum Token { // In practice a string token contains either a `&'static str` or a // `String`. `Cow` is overkill for this because we never modify the data, @@ -229,7 +229,6 @@ pub struct Printer { last_printed: Option, } -#[derive(Clone)] struct BufEntry { token: Token, size: isize, From 3eadc6844bfb4da5ab5e28414eb11ed39fc72e0f Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 10:02:52 +1100 Subject: [PATCH 23/66] Update itertools to 0.11. Because the API for `with_position` improved in 0.11 and I want to use it. --- Cargo.lock | 4 ++-- compiler/rustc_ast_passes/Cargo.toml | 2 +- compiler/rustc_borrowck/Cargo.toml | 2 +- compiler/rustc_codegen_llvm/Cargo.toml | 2 +- compiler/rustc_codegen_ssa/Cargo.toml | 2 +- compiler/rustc_data_structures/Cargo.toml | 2 +- compiler/rustc_mir_transform/Cargo.toml | 2 +- compiler/rustc_passes/Cargo.toml | 2 +- compiler/rustc_transmute/Cargo.toml | 2 +- compiler/rustc_ty_utils/Cargo.toml | 2 +- src/librustdoc/Cargo.toml | 2 +- src/tools/clippy/Cargo.toml | 2 +- src/tools/clippy/clippy_dev/Cargo.toml | 2 +- src/tools/clippy/clippy_lints/Cargo.toml | 2 +- src/tools/clippy/clippy_utils/Cargo.toml | 2 +- src/tools/clippy/declare_clippy_lint/Cargo.toml | 2 +- src/tools/rustfmt/Cargo.toml | 2 +- 17 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ad6dac97a0af..8cb6997ae40e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2060,9 +2060,9 @@ dependencies = [ [[package]] name = "itertools" -version = "0.10.5" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" dependencies = [ "either", ] diff --git a/compiler/rustc_ast_passes/Cargo.toml b/compiler/rustc_ast_passes/Cargo.toml index 0001394c8d38..99e79f65fb4a 100644 --- a/compiler/rustc_ast_passes/Cargo.toml +++ b/compiler/rustc_ast_passes/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start -itertools = "0.10.1" +itertools = "0.11" rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_borrowck/Cargo.toml b/compiler/rustc_borrowck/Cargo.toml index 636817a7ce10..79ad24273250 100644 --- a/compiler/rustc_borrowck/Cargo.toml +++ b/compiler/rustc_borrowck/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start either = "1.5.0" -itertools = "0.10.1" +itertools = "0.11" polonius-engine = "0.13.0" rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_codegen_llvm/Cargo.toml b/compiler/rustc_codegen_llvm/Cargo.toml index 1d309eb908e3..580ef9b06e70 100644 --- a/compiler/rustc_codegen_llvm/Cargo.toml +++ b/compiler/rustc_codegen_llvm/Cargo.toml @@ -10,7 +10,7 @@ test = false # tidy-alphabetical-start bitflags = "1.0" cstr = "0.2" -itertools = "0.10.5" +itertools = "0.11" libc = "0.2" measureme = "10.0.0" object = { version = "0.32.0", default-features = false, features = ["std", "read"] } diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index d385d367f396..0ca19e5fe4a4 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -8,7 +8,7 @@ edition = "2021" ar_archive_writer = "0.1.5" bitflags = "1.2.1" cc = "1.0.69" -itertools = "0.10.1" +itertools = "0.11" jobserver = "0.1.22" pathdiff = "0.2.0" regex = "1.4" diff --git a/compiler/rustc_data_structures/Cargo.toml b/compiler/rustc_data_structures/Cargo.toml index 8d91c4c43768..77d9e491748d 100644 --- a/compiler/rustc_data_structures/Cargo.toml +++ b/compiler/rustc_data_structures/Cargo.toml @@ -10,7 +10,7 @@ bitflags = "1.2.1" elsa = "=1.7.1" ena = "0.14.2" indexmap = { version = "2.0.0" } -itertools = "0.10.1" +itertools = "0.11" jobserver_crate = { version = "0.1.13", package = "jobserver" } libc = "0.2" measureme = "10.0.0" diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml index 0448e9d276d4..ea7f2a413fb7 100644 --- a/compiler/rustc_mir_transform/Cargo.toml +++ b/compiler/rustc_mir_transform/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start either = "1" -itertools = "0.10.1" +itertools = "0.11" rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_passes/Cargo.toml b/compiler/rustc_passes/Cargo.toml index 40c3811e054e..d4cd452e7e2a 100644 --- a/compiler/rustc_passes/Cargo.toml +++ b/compiler/rustc_passes/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start -itertools = "0.10.1" +itertools = "0.11" rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_transmute/Cargo.toml b/compiler/rustc_transmute/Cargo.toml index 07420985a851..066016231fa3 100644 --- a/compiler/rustc_transmute/Cargo.toml +++ b/compiler/rustc_transmute/Cargo.toml @@ -27,5 +27,5 @@ rustc = [ [dev-dependencies] # tidy-alphabetical-start -itertools = "0.10.1" +itertools = "0.11" # tidy-alphabetical-end diff --git a/compiler/rustc_ty_utils/Cargo.toml b/compiler/rustc_ty_utils/Cargo.toml index 7e00f1e0c422..f8eb82da8f68 100644 --- a/compiler/rustc_ty_utils/Cargo.toml +++ b/compiler/rustc_ty_utils/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start -itertools = "0.10.1" +itertools = "0.11" rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml index f3917b978dfd..e13e95ef7088 100644 --- a/src/librustdoc/Cargo.toml +++ b/src/librustdoc/Cargo.toml @@ -9,7 +9,7 @@ path = "lib.rs" [dependencies] arrayvec = { version = "0.7", default-features = false } askama = { version = "0.12", default-features = false, features = ["config"] } -itertools = "0.10.1" +itertools = "0.11" indexmap = "2" minifier = "0.3.0" once_cell = "1.10.0" diff --git a/src/tools/clippy/Cargo.toml b/src/tools/clippy/Cargo.toml index 3b138b480b6f..f6084a462726 100644 --- a/src/tools/clippy/Cargo.toml +++ b/src/tools/clippy/Cargo.toml @@ -37,7 +37,7 @@ toml = "0.7.3" walkdir = "2.3" # This is used by the `collect-metadata` alias. filetime = "0.2" -itertools = "0.10.1" +itertools = "0.11" # UI test dependencies clippy_utils = { path = "clippy_utils" } diff --git a/src/tools/clippy/clippy_dev/Cargo.toml b/src/tools/clippy/clippy_dev/Cargo.toml index c3f8a782d273..ce738e3f4ec7 100644 --- a/src/tools/clippy/clippy_dev/Cargo.toml +++ b/src/tools/clippy/clippy_dev/Cargo.toml @@ -7,7 +7,7 @@ edition = "2021" aho-corasick = "0.7" clap = "4.1.4" indoc = "1.0" -itertools = "0.10.1" +itertools = "0.11" opener = "0.5" shell-escape = "0.1" walkdir = "2.3" diff --git a/src/tools/clippy/clippy_lints/Cargo.toml b/src/tools/clippy/clippy_lints/Cargo.toml index 84246d285c09..a9375214be44 100644 --- a/src/tools/clippy/clippy_lints/Cargo.toml +++ b/src/tools/clippy/clippy_lints/Cargo.toml @@ -14,7 +14,7 @@ cargo_metadata = "0.15.3" clippy_config = { path = "../clippy_config" } clippy_utils = { path = "../clippy_utils" } declare_clippy_lint = { path = "../declare_clippy_lint" } -itertools = "0.10.1" +itertools = "0.11" quine-mc_cluskey = "0.2" regex-syntax = "0.7" serde = { version = "1.0", features = ["derive"] } diff --git a/src/tools/clippy/clippy_utils/Cargo.toml b/src/tools/clippy/clippy_utils/Cargo.toml index d7053d3ff848..5d23326cec89 100644 --- a/src/tools/clippy/clippy_utils/Cargo.toml +++ b/src/tools/clippy/clippy_utils/Cargo.toml @@ -7,7 +7,7 @@ publish = false [dependencies] clippy_config = { path = "../clippy_config" } arrayvec = { version = "0.7", default-features = false } -itertools = "0.10.1" +itertools = "0.11" rustc-semver = "1.1" [features] diff --git a/src/tools/clippy/declare_clippy_lint/Cargo.toml b/src/tools/clippy/declare_clippy_lint/Cargo.toml index 8c1150ed0104..af123e107d5c 100644 --- a/src/tools/clippy/declare_clippy_lint/Cargo.toml +++ b/src/tools/clippy/declare_clippy_lint/Cargo.toml @@ -8,7 +8,7 @@ publish = false proc-macro = true [dependencies] -itertools = "0.10.1" +itertools = "0.11" quote = "1.0.21" syn = "2.0" diff --git a/src/tools/rustfmt/Cargo.toml b/src/tools/rustfmt/Cargo.toml index 00e0ed37a84a..032b9b548104 100644 --- a/src/tools/rustfmt/Cargo.toml +++ b/src/tools/rustfmt/Cargo.toml @@ -43,7 +43,7 @@ diff = "0.1" dirs = "4.0" getopts = "0.2" ignore = "0.4" -itertools = "0.10" +itertools = "0.11" lazy_static = "1.4" regex = "1.7" serde = { version = "1.0.160", features = ["derive"] } From ce363bb6e6b2b50dd897e550f41d366eae52aae2 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 09:59:30 +1100 Subject: [PATCH 24/66] Remove `IterDelimited`. itertools has `with_position` which does the same thing. --- Cargo.lock | 1 + compiler/rustc_ast_pretty/Cargo.toml | 1 + compiler/rustc_ast_pretty/src/pprust/state.rs | 3 -- .../src/pprust/state/delimited.rs | 41 ------------------- .../rustc_ast_pretty/src/pprust/state/expr.rs | 12 +++--- .../rustc_ast_pretty/src/pprust/state/item.rs | 7 ++-- 6 files changed, 13 insertions(+), 52 deletions(-) delete mode 100644 compiler/rustc_ast_pretty/src/pprust/state/delimited.rs diff --git a/Cargo.lock b/Cargo.lock index 8cb6997ae40e..8d54fe7ef763 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3471,6 +3471,7 @@ dependencies = [ name = "rustc_ast_pretty" version = "0.0.0" dependencies = [ + "itertools", "rustc_ast", "rustc_span", "thin-vec", diff --git a/compiler/rustc_ast_pretty/Cargo.toml b/compiler/rustc_ast_pretty/Cargo.toml index af1524c8baa7..12a08f06558b 100644 --- a/compiler/rustc_ast_pretty/Cargo.toml +++ b/compiler/rustc_ast_pretty/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start +itertools = "0.11" rustc_ast = { path = "../rustc_ast" } rustc_span = { path = "../rustc_span" } thin-vec = "0.2.12" diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 0962cb1b8d48..c077c8f8f432 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1,4 +1,3 @@ -mod delimited; mod expr; mod item; @@ -23,8 +22,6 @@ use rustc_span::{BytePos, FileName, Span, DUMMY_SP}; use std::borrow::Cow; use thin_vec::ThinVec; -pub use self::delimited::IterDelimited; - pub enum MacHeader<'a> { Path(&'a ast::Path), Keyword(&'static str), diff --git a/compiler/rustc_ast_pretty/src/pprust/state/delimited.rs b/compiler/rustc_ast_pretty/src/pprust/state/delimited.rs deleted file mode 100644 index fe0640baaa1b..000000000000 --- a/compiler/rustc_ast_pretty/src/pprust/state/delimited.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::iter::Peekable; -use std::mem; -use std::ops::Deref; - -pub struct Delimited { - is_first: bool, - iter: Peekable, -} - -pub trait IterDelimited: Iterator + Sized { - fn delimited(self) -> Delimited { - Delimited { is_first: true, iter: self.peekable() } - } -} - -impl IterDelimited for I {} - -pub struct IteratorItem { - value: T, - pub is_first: bool, - pub is_last: bool, -} - -impl Iterator for Delimited { - type Item = IteratorItem; - - fn next(&mut self) -> Option { - let value = self.iter.next()?; - let is_first = mem::replace(&mut self.is_first, false); - let is_last = self.iter.peek().is_none(); - Some(IteratorItem { value, is_first, is_last }) - } -} - -impl Deref for IteratorItem { - type Target = T; - - fn deref(&self) -> &Self::Target { - &self.value - } -} diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index edbc3500373b..b1ef0764defa 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -1,6 +1,6 @@ use crate::pp::Breaks::Inconsistent; -use crate::pprust::state::{AnnNode, IterDelimited, PrintState, State, INDENT_UNIT}; - +use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; +use itertools::{Itertools, Position}; use rustc_ast::ptr::P; use rustc_ast::token; use rustc_ast::util::literal::escape_byte_str_symbol; @@ -149,10 +149,12 @@ impl<'a> State<'a> { return; } self.cbox(0); - for field in fields.iter().delimited() { + for (pos, field) in fields.iter().with_position() { + let is_first = matches!(pos, Position::First | Position::Only); + let is_last = matches!(pos, Position::Last | Position::Only); self.maybe_print_comment(field.span.hi()); self.print_outer_attributes(&field.attrs); - if field.is_first { + if is_first { self.space_if_not_bol(); } if !field.is_shorthand { @@ -160,7 +162,7 @@ impl<'a> State<'a> { self.word_nbsp(":"); } self.print_expr(&field.expr); - if !field.is_last || has_rest { + if !is_last || has_rest { self.word_space(","); } else { self.trailing_comma_or_space(); diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 3393f034bc3b..8c0e7ec15c96 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -1,8 +1,8 @@ use crate::pp::Breaks::Inconsistent; -use crate::pprust::state::delimited::IterDelimited; use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; use ast::StaticItem; +use itertools::{Itertools, Position}; use rustc_ast as ast; use rustc_ast::GenericBound; use rustc_ast::ModKind; @@ -712,9 +712,10 @@ impl<'a> State<'a> { self.word("{"); self.zerobreak(); self.ibox(0); - for use_tree in items.iter().delimited() { + for (pos, use_tree) in items.iter().with_position() { + let is_last = matches!(pos, Position::Last | Position::Only); self.print_use_tree(&use_tree.0); - if !use_tree.is_last { + if !is_last { self.word(","); if let ast::UseTreeKind::Nested(_) = use_tree.0.kind { self.hardbreak(); From 33cee0b22c8831b8521fd150e6be85a6425be037 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 10:44:08 +1100 Subject: [PATCH 25/66] Remove `NO_ANN`. This makes `rustc_hir_pretty` more like `rustc_ast_pretty`. --- compiler/rustc_hir_pretty/src/lib.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 5f82d9f06c6e..5996d60b5254 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -49,8 +49,8 @@ pub trait PpAnn { } pub struct NoAnn; + impl PpAnn for NoAnn {} -pub const NO_ANN: &dyn PpAnn = &NoAnn; impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> { fn nested(&self, state: &mut State<'_>, nested: Nested) { @@ -183,15 +183,15 @@ where } pub fn ty_to_string(ty: &hir::Ty<'_>) -> String { - to_string(NO_ANN, |s| s.print_type(ty)) + to_string(&NoAnn, |s| s.print_type(ty)) } pub fn qpath_to_string(segment: &hir::QPath<'_>) -> String { - to_string(NO_ANN, |s| s.print_qpath(segment, false)) + to_string(&NoAnn, |s| s.print_qpath(segment, false)) } pub fn pat_to_string(pat: &hir::Pat<'_>) -> String { - to_string(NO_ANN, |s| s.print_pat(pat)) + to_string(&NoAnn, |s| s.print_pat(pat)) } impl<'a> State<'a> { From d9443f71c7dc55b4e57e8ec02e762704482f1dce Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 09:22:10 +1100 Subject: [PATCH 26/66] Remove or downgrade unnecessary `pub` visibility markers. --- compiler/rustc_ast_pretty/src/pp.rs | 14 ++-- .../rustc_ast_pretty/src/pp/convenience.rs | 2 +- compiler/rustc_ast_pretty/src/pprust/state.rs | 66 +++++++++---------- .../rustc_ast_pretty/src/pprust/state/expr.rs | 4 +- .../rustc_ast_pretty/src/pprust/state/item.rs | 8 +-- 5 files changed, 44 insertions(+), 50 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pp.rs b/compiler/rustc_ast_pretty/src/pp.rs index 249d02a76da3..96f5eff68901 100644 --- a/compiler/rustc_ast_pretty/src/pp.rs +++ b/compiler/rustc_ast_pretty/src/pp.rs @@ -165,20 +165,20 @@ enum IndentStyle { } #[derive(Clone, Copy, Default, PartialEq)] -pub struct BreakToken { +pub(crate) struct BreakToken { offset: isize, blank_space: isize, pre_break: Option, } #[derive(Clone, Copy, PartialEq)] -pub struct BeginToken { +pub(crate) struct BeginToken { indent: IndentStyle, breaks: Breaks, } #[derive(PartialEq)] -pub enum Token { +pub(crate) enum Token { // In practice a string token contains either a `&'static str` or a // `String`. `Cow` is overkill for this because we never modify the data, // but it's more convenient than rolling our own more specialized type. @@ -250,16 +250,16 @@ impl Printer { } } - pub fn last_token(&self) -> Option<&Token> { + pub(crate) fn last_token(&self) -> Option<&Token> { self.last_token_still_buffered().or_else(|| self.last_printed.as_ref()) } - pub fn last_token_still_buffered(&self) -> Option<&Token> { + pub(crate) fn last_token_still_buffered(&self) -> Option<&Token> { self.buf.last().map(|last| &last.token) } /// Be very careful with this! - pub fn replace_last_token_still_buffered(&mut self, token: Token) { + pub(crate) fn replace_last_token_still_buffered(&mut self, token: Token) { self.buf.last_mut().unwrap().token = token; } @@ -313,7 +313,7 @@ impl Printer { } } - pub fn offset(&mut self, offset: isize) { + pub(crate) fn offset(&mut self, offset: isize) { if let Some(BufEntry { token: Token::Break(token), .. }) = &mut self.buf.last_mut() { token.offset += offset; } diff --git a/compiler/rustc_ast_pretty/src/pp/convenience.rs b/compiler/rustc_ast_pretty/src/pp/convenience.rs index 93310dd45c57..c4c4fdce7fef 100644 --- a/compiler/rustc_ast_pretty/src/pp/convenience.rs +++ b/compiler/rustc_ast_pretty/src/pp/convenience.rs @@ -66,7 +66,7 @@ impl Printer { } } - pub fn hardbreak_tok_offset(off: isize) -> Token { + pub(crate) fn hardbreak_tok_offset(off: isize) -> Token { Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY, diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index c077c8f8f432..bbc91226183c 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -43,8 +43,7 @@ pub trait PpAnn { fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} } -#[derive(Copy, Clone)] -pub struct NoAnn; +struct NoAnn; impl PpAnn for NoAnn {} @@ -61,11 +60,11 @@ impl<'a> Comments<'a> { } // FIXME: This shouldn't probably clone lmao - pub fn next(&self) -> Option { + fn next(&self) -> Option { self.comments.get(self.current).cloned() } - pub fn trailing_comment( + fn trailing_comment( &self, span: rustc_span::Span, next_pos: Option, @@ -92,7 +91,7 @@ pub struct State<'a> { ann: &'a (dyn PpAnn + 'a), } -pub(crate) const INDENT_UNIT: isize = 4; +const INDENT_UNIT: isize = 4; /// Requires you to pass an input filename and reader so that /// it can scan the input text for comments to copy forward. @@ -217,7 +216,7 @@ fn doc_comment_to_string( } } -pub fn literal_to_string(lit: token::Lit) -> String { +fn literal_to_string(lit: token::Lit) -> String { let token::Lit { kind, symbol, suffix } = lit; let mut out = match kind { token::Byte => format!("b'{symbol}'"), @@ -976,13 +975,8 @@ impl<'a> State<'a> { State { s: pp::Printer::new(), comments: None, ann: &NoAnn } } - pub(crate) fn commasep_cmnt( - &mut self, - b: Breaks, - elts: &[T], - mut op: F, - mut get_span: G, - ) where + fn commasep_cmnt(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G) + where F: FnMut(&mut State<'_>, &T), G: FnMut(&T) -> rustc_span::Span, { @@ -1002,7 +996,7 @@ impl<'a> State<'a> { self.end(); } - pub(crate) fn commasep_exprs(&mut self, b: Breaks, exprs: &[P]) { + fn commasep_exprs(&mut self, b: Breaks, exprs: &[P]) { self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span) } @@ -1153,7 +1147,7 @@ impl<'a> State<'a> { self.print_trait_ref(&t.trait_ref) } - pub(crate) fn print_stmt(&mut self, st: &ast::Stmt) { + fn print_stmt(&mut self, st: &ast::Stmt) { self.maybe_print_comment(st.span.lo()); match &st.kind { ast::StmtKind::Local(loc) => { @@ -1208,19 +1202,19 @@ impl<'a> State<'a> { self.maybe_print_trailing_comment(st.span, None) } - pub(crate) fn print_block(&mut self, blk: &ast::Block) { + fn print_block(&mut self, blk: &ast::Block) { self.print_block_with_attrs(blk, &[]) } - pub(crate) fn print_block_unclosed_indent(&mut self, blk: &ast::Block) { + fn print_block_unclosed_indent(&mut self, blk: &ast::Block) { self.print_block_maybe_unclosed(blk, &[], false) } - pub(crate) fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) { + fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) { self.print_block_maybe_unclosed(blk, attrs, true) } - pub(crate) fn print_block_maybe_unclosed( + fn print_block_maybe_unclosed( &mut self, blk: &ast::Block, attrs: &[ast::Attribute], @@ -1254,7 +1248,7 @@ impl<'a> State<'a> { } /// Print a `let pat = expr` expression. - pub(crate) fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) { + fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) { self.word("let "); self.print_pat(pat); self.space(); @@ -1263,7 +1257,7 @@ impl<'a> State<'a> { self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals()) } - pub(crate) fn print_mac(&mut self, m: &ast::MacCall) { + fn print_mac(&mut self, m: &ast::MacCall) { self.print_mac_common( Some(MacHeader::Path(&m.path)), true, @@ -1404,7 +1398,7 @@ impl<'a> State<'a> { self.pclose(); } - pub(crate) fn print_local_decl(&mut self, loc: &ast::Local) { + fn print_local_decl(&mut self, loc: &ast::Local) { self.print_pat(&loc.pat); if let Some(ty) = &loc.ty { self.word_space(":"); @@ -1412,7 +1406,7 @@ impl<'a> State<'a> { } } - pub(crate) fn print_name(&mut self, name: Symbol) { + fn print_name(&mut self, name: Symbol) { self.word(name.to_string()); self.ann.post(self, AnnNode::Name(&name)) } @@ -1436,7 +1430,7 @@ impl<'a> State<'a> { } } - pub(crate) fn print_pat(&mut self, pat: &ast::Pat) { + fn print_pat(&mut self, pat: &ast::Pat) { self.maybe_print_comment(pat.span.lo()); self.ann.pre(self, AnnNode::Pat(pat)); /* Pat isn't normalized, but the beauty of it @@ -1589,7 +1583,7 @@ impl<'a> State<'a> { } } - pub(crate) fn print_asyncness(&mut self, asyncness: ast::Async) { + fn print_asyncness(&mut self, asyncness: ast::Async) { if asyncness.is_async() { self.word_nbsp("async"); } @@ -1634,11 +1628,11 @@ impl<'a> State<'a> { } } - pub(crate) fn print_lifetime(&mut self, lifetime: ast::Lifetime) { + fn print_lifetime(&mut self, lifetime: ast::Lifetime) { self.print_name(lifetime.ident.name) } - pub(crate) fn print_lifetime_bounds(&mut self, bounds: &ast::GenericBounds) { + fn print_lifetime_bounds(&mut self, bounds: &ast::GenericBounds) { for (i, bound) in bounds.iter().enumerate() { if i != 0 { self.word(" + "); @@ -1650,7 +1644,7 @@ impl<'a> State<'a> { } } - pub(crate) fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) { + fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) { if generic_params.is_empty() { return; } @@ -1714,12 +1708,12 @@ impl<'a> State<'a> { } } - pub(crate) fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) { + fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) { self.print_mutability(mt.mutbl, print_const); self.print_type(&mt.ty) } - pub(crate) fn print_param(&mut self, input: &ast::Param, is_closure: bool) { + fn print_param(&mut self, input: &ast::Param, is_closure: bool) { self.ibox(INDENT_UNIT); self.print_outer_attributes_inline(&input.attrs); @@ -1747,7 +1741,7 @@ impl<'a> State<'a> { self.end(); } - pub(crate) fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) { + fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) { if let ast::FnRetTy::Ty(ty) = fn_ret_ty { self.space_if_not_bol(); self.ibox(INDENT_UNIT); @@ -1758,7 +1752,7 @@ impl<'a> State<'a> { } } - pub(crate) fn print_ty_fn( + fn print_ty_fn( &mut self, ext: ast::Extern, unsafety: ast::Unsafe, @@ -1782,7 +1776,7 @@ impl<'a> State<'a> { self.end(); } - pub(crate) fn print_fn_header_info(&mut self, header: ast::FnHeader) { + fn print_fn_header_info(&mut self, header: ast::FnHeader) { self.print_constness(header.constness); self.print_asyncness(header.asyncness); self.print_unsafety(header.unsafety); @@ -1802,21 +1796,21 @@ impl<'a> State<'a> { self.word("fn") } - pub(crate) fn print_unsafety(&mut self, s: ast::Unsafe) { + fn print_unsafety(&mut self, s: ast::Unsafe) { match s { ast::Unsafe::No => {} ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"), } } - pub(crate) fn print_constness(&mut self, s: ast::Const) { + fn print_constness(&mut self, s: ast::Const) { match s { ast::Const::No => {} ast::Const::Yes(_) => self.word_nbsp("const"), } } - pub(crate) fn print_is_auto(&mut self, s: ast::IsAuto) { + fn print_is_auto(&mut self, s: ast::IsAuto) { match s { ast::IsAuto::Yes => self.word_nbsp("auto"), ast::IsAuto::No => {} diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index b1ef0764defa..ed9b68a1d5a9 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -281,7 +281,7 @@ impl<'a> State<'a> { self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) } - pub fn print_expr(&mut self, expr: &ast::Expr) { + pub(super) fn print_expr(&mut self, expr: &ast::Expr) { self.print_expr_outer_attr_style(expr, true) } @@ -681,7 +681,7 @@ impl<'a> State<'a> { } } -pub fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> String { +fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> String { let mut template = "\"".to_string(); for piece in pieces { match piece { diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 8c0e7ec15c96..a2be8845f8a5 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -20,7 +20,7 @@ impl<'a> State<'a> { } } - pub(crate) fn print_foreign_item(&mut self, item: &ast::ForeignItem) { + fn print_foreign_item(&mut self, item: &ast::ForeignItem) { let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item; self.ann.pre(self, AnnNode::SubItem(id)); self.hardbreak_if_not_bol(); @@ -518,7 +518,7 @@ impl<'a> State<'a> { } } - pub(crate) fn print_assoc_item(&mut self, item: &ast::AssocItem) { + fn print_assoc_item(&mut self, item: &ast::AssocItem) { let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item; self.ann.pre(self, AnnNode::SubItem(id)); self.hardbreak_if_not_bol(); @@ -621,7 +621,7 @@ impl<'a> State<'a> { self.print_where_clause_parts(where_clause.has_where_token, &where_clause.predicates); } - pub(crate) fn print_where_clause_parts( + fn print_where_clause_parts( &mut self, has_where_token: bool, predicates: &[ast::WherePredicate], @@ -668,7 +668,7 @@ impl<'a> State<'a> { } } - pub fn print_where_bound_predicate( + pub(crate) fn print_where_bound_predicate( &mut self, where_bound_predicate: &ast::WhereBoundPredicate, ) { From c6a902710252bd4b01c9a369c16a5b35c3758a04 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 11:46:02 +1100 Subject: [PATCH 27/66] Remove unused `PrintState::generic_params_to_string` method. --- compiler/rustc_ast_pretty/src/pprust/state.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index bbc91226183c..98a2fe92d408 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -886,10 +886,6 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere Self::to_string(|s| s.print_foreign_item(i)) } - fn generic_params_to_string(&self, generic_params: &[ast::GenericParam]) -> String { - Self::to_string(|s| s.print_generic_params(generic_params)) - } - fn path_to_string(&self, p: &ast::Path) -> String { Self::to_string(|s| s.print_path(p, false, 0)) } From e16b52d4f05d4c41b3f7a3c2ba65fb6495979568 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 12:22:05 +1100 Subject: [PATCH 28/66] Streamline `PrintState`. `PrintState` is a trait containing code that can be used by both AST and HIR pretty-printing. But several of its methods are only used by AST printing. This commit moves those methods out of the trait and into the AST `State` impl, so they are not exposed unnecessarily. This commit also removes four unused methods: `param_to_string`, `foreign_item_to_string`, `assoc_item_to_string`, and `print_inner_attributes_inline`. --- compiler/rustc_ast_pretty/src/pprust/state.rs | 182 ++++++++---------- 1 file changed, 83 insertions(+), 99 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 98a2fe92d408..9d94eb699fe2 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -397,15 +397,6 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere } } - fn print_meta_item_lit(&mut self, lit: &ast::MetaItemLit) { - self.print_token_literal(lit.as_token_lit(), lit.span) - } - - fn print_token_literal(&mut self, token_lit: token::Lit, span: Span) { - self.maybe_print_comment(span.lo()); - self.word(token_lit.to_string()) - } - fn print_string(&mut self, st: &str, style: ast::StrStyle) { let st = match style { ast::StrStyle::Cooked => format!("\"{}\"", st.escape_debug()), @@ -416,30 +407,14 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere self.word(st) } - fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) { - self.print_string(sym.as_str(), style); - } - fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> bool { self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true) } - fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) -> bool { - self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false) - } - fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> bool { self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true) } - fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool { - self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true) - } - - fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool { - self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true) - } - fn print_either_attributes( &mut self, attrs: &[ast::Attribute], @@ -463,10 +438,6 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere printed } - fn print_attribute(&mut self, attr: &ast::Attribute) { - self.print_attribute_inline(attr, false) - } - fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) { if !is_inline { self.hardbreak_if_not_bol(); @@ -521,33 +492,6 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere self.end(); } - fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) { - match item { - ast::NestedMetaItem::MetaItem(mi) => self.print_meta_item(mi), - ast::NestedMetaItem::Lit(lit) => self.print_meta_item_lit(lit), - } - } - - fn print_meta_item(&mut self, item: &ast::MetaItem) { - self.ibox(INDENT_UNIT); - match &item.kind { - ast::MetaItemKind::Word => self.print_path(&item.path, false, 0), - ast::MetaItemKind::NameValue(value) => { - self.print_path(&item.path, false, 0); - self.space(); - self.word_space("="); - self.print_meta_item_lit(value); - } - ast::MetaItemKind::List(items) => { - self.print_path(&item.path, false, 0); - self.popen(); - self.commasep(Consistent, items, |s, i| s.print_meta_list_item(i)); - self.pclose(); - } - } - self.end(); - } - /// This doesn't deserve to be called "pretty" printing, but it should be /// meaning-preserving. A quick hack that might help would be to look at the /// spans embedded in the TTs to decide where to put spaces and newlines. @@ -839,17 +783,6 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere Self::to_string(|s| s.print_type(ty)) } - fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String { - Self::to_string(|s| s.print_type_bounds(bounds)) - } - - fn where_bound_predicate_to_string( - &self, - where_bound_predicate: &ast::WhereBoundPredicate, - ) -> String { - Self::to_string(|s| s.print_where_bound_predicate(where_bound_predicate)) - } - fn pat_to_string(&self, pat: &ast::Pat) -> String { Self::to_string(|s| s.print_pat(pat)) } @@ -862,14 +795,6 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere Self::to_string(|s| s.print_meta_item_lit(lit)) } - fn tt_to_string(&self, tt: &TokenTree) -> String { - Self::to_string(|s| s.print_tt(tt, false)) - } - - fn tts_to_string(&self, tokens: &TokenStream) -> String { - Self::to_string(|s| s.print_tts(tokens, false)) - } - fn stmt_to_string(&self, stmt: &ast::Stmt) -> String { Self::to_string(|s| s.print_stmt(stmt)) } @@ -878,22 +803,10 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere Self::to_string(|s| s.print_item(i)) } - fn assoc_item_to_string(&self, i: &ast::AssocItem) -> String { - Self::to_string(|s| s.print_assoc_item(i)) - } - - fn foreign_item_to_string(&self, i: &ast::ForeignItem) -> String { - Self::to_string(|s| s.print_foreign_item(i)) - } - fn path_to_string(&self, p: &ast::Path) -> String { Self::to_string(|s| s.print_path(p, false, 0)) } - fn path_segment_to_string(&self, p: &ast::PathSegment) -> String { - Self::to_string(|s| s.print_path_segment(p, false)) - } - fn vis_to_string(&self, v: &ast::Visibility) -> String { Self::to_string(|s| s.print_visibility(v)) } @@ -908,22 +821,10 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere }) } - fn meta_list_item_to_string(&self, li: &ast::NestedMetaItem) -> String { - Self::to_string(|s| s.print_meta_list_item(li)) - } - fn attr_item_to_string(&self, ai: &ast::AttrItem) -> String { Self::to_string(|s| s.print_attr_item(ai, ai.path.span)) } - fn attribute_to_string(&self, attr: &ast::Attribute) -> String { - Self::to_string(|s| s.print_attribute(attr)) - } - - fn param_to_string(&self, arg: &ast::Param) -> String { - Self::to_string(|s| s.print_param(arg, false)) - } - fn to_string(f: impl FnOnce(&mut State<'_>)) -> String { let mut printer = State::new(); f(&mut printer); @@ -1812,4 +1713,87 @@ impl<'a> State<'a> { ast::IsAuto::No => {} } } + + fn print_meta_item_lit(&mut self, lit: &ast::MetaItemLit) { + self.print_token_literal(lit.as_token_lit(), lit.span) + } + + fn print_token_literal(&mut self, token_lit: token::Lit, span: Span) { + self.maybe_print_comment(span.lo()); + self.word(token_lit.to_string()) + } + + fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) { + self.print_string(sym.as_str(), style); + } + + fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) -> bool { + self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false) + } + + fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool { + self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true) + } + + fn print_attribute(&mut self, attr: &ast::Attribute) { + self.print_attribute_inline(attr, false) + } + + fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) { + match item { + ast::NestedMetaItem::MetaItem(mi) => self.print_meta_item(mi), + ast::NestedMetaItem::Lit(lit) => self.print_meta_item_lit(lit), + } + } + + fn print_meta_item(&mut self, item: &ast::MetaItem) { + self.ibox(INDENT_UNIT); + match &item.kind { + ast::MetaItemKind::Word => self.print_path(&item.path, false, 0), + ast::MetaItemKind::NameValue(value) => { + self.print_path(&item.path, false, 0); + self.space(); + self.word_space("="); + self.print_meta_item_lit(value); + } + ast::MetaItemKind::List(items) => { + self.print_path(&item.path, false, 0); + self.popen(); + self.commasep(Consistent, items, |s, i| s.print_meta_list_item(i)); + self.pclose(); + } + } + self.end(); + } + + pub(crate) fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String { + Self::to_string(|s| s.print_type_bounds(bounds)) + } + + pub(crate) fn where_bound_predicate_to_string( + &self, + where_bound_predicate: &ast::WhereBoundPredicate, + ) -> String { + Self::to_string(|s| s.print_where_bound_predicate(where_bound_predicate)) + } + + pub(crate) fn tt_to_string(&self, tt: &TokenTree) -> String { + Self::to_string(|s| s.print_tt(tt, false)) + } + + pub(crate) fn tts_to_string(&self, tokens: &TokenStream) -> String { + Self::to_string(|s| s.print_tts(tokens, false)) + } + + pub(crate) fn path_segment_to_string(&self, p: &ast::PathSegment) -> String { + Self::to_string(|s| s.print_path_segment(p, false)) + } + + pub(crate) fn meta_list_item_to_string(&self, li: &ast::NestedMetaItem) -> String { + Self::to_string(|s| s.print_meta_list_item(li)) + } + + pub(crate) fn attribute_to_string(&self, attr: &ast::Attribute) -> String { + Self::to_string(|s| s.print_attribute(attr)) + } } From 10c8b56af1d0157708c0a81e9d05e9402bc4fef2 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 13:32:41 +1100 Subject: [PATCH 29/66] Factor out common code in `PrintState`. The AST and HIR versions of `State::print_ident` are textually identical, but the types differ slightly. This commit factors out the common code they both have by replacing `print_ident` with `ann_post`, which is a smaller function that still captures the type difference. --- compiler/rustc_ast_pretty/src/pprust/state.rs | 12 ++++++++---- compiler/rustc_hir_pretty/src/lib.rs | 7 +++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 9d94eb699fe2..f29e8b546812 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -258,9 +258,14 @@ impl std::ops::DerefMut for State<'_> { pub trait PrintState<'a>: std::ops::Deref + std::ops::DerefMut { fn comments(&mut self) -> &mut Option>; - fn print_ident(&mut self, ident: Ident); + fn ann_post(&mut self, ident: Ident); fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool); + fn print_ident(&mut self, ident: Ident) { + self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string()); + self.ann_post(ident) + } + fn strsep( &mut self, sep: &'static str, @@ -837,9 +842,8 @@ impl<'a> PrintState<'a> for State<'a> { &mut self.comments } - fn print_ident(&mut self, ident: Ident) { - self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string()); - self.ann.post(self, AnnNode::Ident(&ident)) + fn ann_post(&mut self, ident: Ident) { + self.ann.post(self, AnnNode::Ident(&ident)); } fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) { diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 5996d60b5254..a1a218a421b8 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -12,7 +12,7 @@ use rustc_hir::LifetimeParamKind; use rustc_hir::{BindingAnnotation, ByRef, GenericArg, GenericParam, GenericParamKind, Node, Term}; use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier}; use rustc_span::source_map::SourceMap; -use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol}; +use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::{self, FileName}; use rustc_target::spec::abi::Abi; @@ -136,9 +136,8 @@ impl<'a> PrintState<'a> for State<'a> { &mut self.comments } - fn print_ident(&mut self, ident: Ident) { - self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string()); - self.ann.post(self, AnnNode::Name(&ident.name)) + fn ann_post(&mut self, ident: Ident) { + self.ann.post(self, AnnNode::Name(&ident.name)); } fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) { From e11d8d147b94043d54d0a6c8ff0bdb0568b794ca Mon Sep 17 00:00:00 2001 From: Arlie Davis Date: Fri, 17 Nov 2023 10:05:38 -0800 Subject: [PATCH 30/66] Add support for generating the EHCont section In the future Windows will enable Control-flow Enforcement Technology (CET aka Shadow Stacks). To protect the path where the context is updated during exception handling, the binary is required to enumerate valid unwind entrypoints in a dedicated section which is validated when the context is being set during exception handling. The required support for EHCONT has already been merged into LLVM, long ago. This change adds the Rust codegen option to enable it. Reference: * https://reviews.llvm.org/D40223 This also adds a new `ehcont-guard` option to the bootstrap config which enables EHCont Guard when building std. --- compiler/rustc_codegen_llvm/src/context.rs | 9 ++++++++ compiler/rustc_codegen_ssa/src/back/link.rs | 5 +++++ compiler/rustc_codegen_ssa/src/back/linker.rs | 21 +++++++++++++++++++ compiler/rustc_session/src/options.rs | 2 ++ config.example.toml | 4 ++++ src/bootstrap/src/core/builder.rs | 12 ++++++++++- src/bootstrap/src/core/config/config.rs | 3 +++ src/bootstrap/src/tests/builder.rs | 2 +- tests/codegen/ehcontguard_disabled.rs | 10 +++++++++ tests/codegen/ehcontguard_enabled.rs | 10 +++++++++ 10 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 tests/codegen/ehcontguard_disabled.rs create mode 100644 tests/codegen/ehcontguard_enabled.rs diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 242c6aed906b..883a4b5f6fb0 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -350,6 +350,15 @@ pub unsafe fn create_module<'ll>( 1, ); } + // Set module flag to enable Windows EHCont Guard (/guard:ehcont). + if sess.opts.cg.ehcont_guard { + llvm::LLVMRustAddModuleFlag( + llmod, + llvm::LLVMModFlagBehavior::Warning, + "ehcontguard\0".as_ptr() as *const _, + 1, + ) + } // Insert `llvm.ident` metadata. // diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 33e8f352cd8a..e571912973cc 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -2378,6 +2378,11 @@ fn add_order_independent_options( cmd.control_flow_guard(); } + // OBJECT-FILES-NO, AUDIT-ORDER + if sess.opts.cg.ehcont_guard { + cmd.ehcont_guard(); + } + add_rpath_args(cmd, sess, codegen_results, out_filename); } diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs index 09434513e31e..73c4aa9712d0 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker.rs @@ -185,6 +185,7 @@ pub trait Linker { fn optimize(&mut self); fn pgo_gen(&mut self); fn control_flow_guard(&mut self); + fn ehcont_guard(&mut self); fn debuginfo(&mut self, strip: Strip, natvis_debugger_visualizers: &[PathBuf]); fn no_crt_objects(&mut self); fn no_default_libraries(&mut self); @@ -605,6 +606,8 @@ impl<'a> Linker for GccLinker<'a> { fn control_flow_guard(&mut self) {} + fn ehcont_guard(&mut self) {} + fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) { // MacOS linker doesn't support stripping symbols directly anymore. if self.sess.target.is_like_osx { @@ -914,6 +917,12 @@ impl<'a> Linker for MsvcLinker<'a> { self.cmd.arg("/guard:cf"); } + fn ehcont_guard(&mut self) { + if self.sess.target.pointer_width == 64 { + self.cmd.arg("/guard:ehcont"); + } + } + fn debuginfo(&mut self, strip: Strip, natvis_debugger_visualizers: &[PathBuf]) { match strip { Strip::None => { @@ -1127,6 +1136,8 @@ impl<'a> Linker for EmLinker<'a> { fn control_flow_guard(&mut self) {} + fn ehcont_guard(&mut self) {} + fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) { // Preserve names or generate source maps depending on debug info // For more information see https://emscripten.org/docs/tools_reference/emcc.html#emcc-g @@ -1319,6 +1330,8 @@ impl<'a> Linker for WasmLd<'a> { fn control_flow_guard(&mut self) {} + fn ehcont_guard(&mut self) {} + fn no_crt_objects(&mut self) {} fn no_default_libraries(&mut self) {} @@ -1472,6 +1485,8 @@ impl<'a> Linker for L4Bender<'a> { fn control_flow_guard(&mut self) {} + fn ehcont_guard(&mut self) {} + fn no_crt_objects(&mut self) {} } @@ -1613,6 +1628,8 @@ impl<'a> Linker for AixLinker<'a> { fn control_flow_guard(&mut self) {} + fn ehcont_guard(&mut self) {} + fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) { match strip { Strip::None => {} @@ -1835,6 +1852,8 @@ impl<'a> Linker for PtxLinker<'a> { fn control_flow_guard(&mut self) {} + fn ehcont_guard(&mut self) {} + fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, _symbols: &[String]) {} fn subsystem(&mut self, _subsystem: &str) {} @@ -1931,6 +1950,8 @@ impl<'a> Linker for BpfLinker<'a> { fn control_flow_guard(&mut self) {} + fn ehcont_guard(&mut self) {} + fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) { let path = tmpdir.join("symbols"); let res: io::Result<()> = try { diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index b824eb51ef7b..924bd97b4d54 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1387,6 +1387,8 @@ options! { "allow the linker to link its default libraries (default: no)"), dlltool: Option = (None, parse_opt_pathbuf, [UNTRACKED], "import library generation tool (ignored except when targeting windows-gnu)"), + ehcont_guard: bool = (false, parse_bool, [TRACKED], + "generate Windows EHCont Guard tables"), embed_bitcode: bool = (true, parse_bool, [TRACKED], "emit bitcode in rlibs (default: yes)"), extra_filename: String = (String::new(), parse_string, [UNTRACKED], diff --git a/config.example.toml b/config.example.toml index 170856bd97db..5f9ae039b252 100644 --- a/config.example.toml +++ b/config.example.toml @@ -686,6 +686,10 @@ change-id = 116881 # This only applies from stage 1 onwards, and only for Windows targets. #control-flow-guard = false +# Enable Windows EHCont Guard checks in the standard library. +# This only applies from stage 1 onwards, and only for Windows targets. +#ehcont-guard = false + # Enable symbol-mangling-version v0. This can be helpful when profiling rustc, # as generics will be preserved in symbols (rather than erased into opaque T). # When no setting is given, the new scheme will be used when compiling the diff --git a/src/bootstrap/src/core/builder.rs b/src/bootstrap/src/core/builder.rs index c755324df1a5..de35e97848af 100644 --- a/src/bootstrap/src/core/builder.rs +++ b/src/bootstrap/src/core/builder.rs @@ -1964,6 +1964,12 @@ impl<'a> Builder<'a> { rustflags.arg("-Ccontrol-flow-guard"); } + // Same for EHCont Guard (this is not combined with the previous if-statement to make + // merges with upstream easier). + if cfg!(windows) && mode == Mode::Std && self.config.ehcont_guard && compiler.stage >= 1 { + rustflags.arg("-Cehcont-guard"); + } + // For `cargo doc` invocations, make rustdoc print the Rust version into the docs // This replaces spaces with tabs because RUSTDOCFLAGS does not // support arguments with regular spaces. Hopefully someday Cargo will @@ -2172,7 +2178,11 @@ impl<'a> Builder<'a> { } // Only execute if it's supposed to run as default - if desc.default && should_run.is_really_default() { self.ensure(step) } else { None } + if desc.default && should_run.is_really_default() { + self.ensure(step) + } else { + None + } } /// Checks if any of the "should_run" paths is in the `Builder` paths. diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index fa8b0b20cec4..9ef90798590c 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -248,6 +248,7 @@ pub struct Config { pub local_rebuild: bool, pub jemalloc: bool, pub control_flow_guard: bool, + pub ehcont_guard: bool, // dist misc pub dist_sign_folder: Option, @@ -1019,6 +1020,7 @@ define_config! { test_compare_mode: Option = "test-compare-mode", llvm_libunwind: Option = "llvm-libunwind", control_flow_guard: Option = "control-flow-guard", + ehcont_guard: Option = "ehcont-guard", new_symbol_mangling: Option = "new-symbol-mangling", profile_generate: Option = "profile-generate", profile_use: Option = "profile-use", @@ -1452,6 +1454,7 @@ impl Config { config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit; set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo); set(&mut config.control_flow_guard, rust.control_flow_guard); + set(&mut config.ehcont_guard, rust.ehcont_guard); config.llvm_libunwind_default = rust .llvm_libunwind .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")); diff --git a/src/bootstrap/src/tests/builder.rs b/src/bootstrap/src/tests/builder.rs index 96139f7b099c..744015e8e820 100644 --- a/src/bootstrap/src/tests/builder.rs +++ b/src/bootstrap/src/tests/builder.rs @@ -1,6 +1,6 @@ use super::*; -use crate::core::config::{Config, DryRun, TargetSelection}; use crate::core::build_steps::doc::DocumentationFormat; +use crate::core::config::{Config, DryRun, TargetSelection}; use std::thread; fn configure(cmd: &str, host: &[&str], target: &[&str]) -> Config { diff --git a/tests/codegen/ehcontguard_disabled.rs b/tests/codegen/ehcontguard_disabled.rs new file mode 100644 index 000000000000..7773384e5ead --- /dev/null +++ b/tests/codegen/ehcontguard_disabled.rs @@ -0,0 +1,10 @@ +// compile-flags: + +#![crate_type = "lib"] + +// A basic test function. +pub fn test() { +} + +// Ensure the module flag ehcontguard is not present +// CHECK-NOT: !"ehcontguard" diff --git a/tests/codegen/ehcontguard_enabled.rs b/tests/codegen/ehcontguard_enabled.rs new file mode 100644 index 000000000000..5e7ea90940e7 --- /dev/null +++ b/tests/codegen/ehcontguard_enabled.rs @@ -0,0 +1,10 @@ +// compile-flags: -C ehcont_guard + +#![crate_type = "lib"] + +// A basic test function. +pub fn test() { +} + +// Ensure the module flag ehcontguard=1 is present +// CHECK: !"ehcontguard", i32 1 From d582f1092b524ed8aff86193928a1c7f871b11cf Mon Sep 17 00:00:00 2001 From: Arlie Davis Date: Fri, 17 Nov 2023 12:54:20 -0800 Subject: [PATCH 31/66] x.py fmt --- src/bootstrap/src/core/builder.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/bootstrap/src/core/builder.rs b/src/bootstrap/src/core/builder.rs index de35e97848af..5fd0d6a50ca6 100644 --- a/src/bootstrap/src/core/builder.rs +++ b/src/bootstrap/src/core/builder.rs @@ -2178,11 +2178,7 @@ impl<'a> Builder<'a> { } // Only execute if it's supposed to run as default - if desc.default && should_run.is_really_default() { - self.ensure(step) - } else { - None - } + if desc.default && should_run.is_really_default() { self.ensure(step) } else { None } } /// Checks if any of the "should_run" paths is in the `Builder` paths. From 9429d68842a90fec21b5bed7419840bd86baaeab Mon Sep 17 00:00:00 2001 From: Arlie Davis Date: Tue, 21 Nov 2023 14:24:23 -0800 Subject: [PATCH 32/66] convert ehcont-guard to an unstable option --- compiler/rustc_codegen_llvm/src/context.rs | 3 ++- compiler/rustc_codegen_ssa/src/back/link.rs | 2 +- compiler/rustc_session/src/options.rs | 4 ++-- tests/codegen/ehcontguard_enabled.rs | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 883a4b5f6fb0..e6c5085cc0ef 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -350,8 +350,9 @@ pub unsafe fn create_module<'ll>( 1, ); } + // Set module flag to enable Windows EHCont Guard (/guard:ehcont). - if sess.opts.cg.ehcont_guard { + if sess.opts.unstable_opts.ehcont_guard { llvm::LLVMRustAddModuleFlag( llmod, llvm::LLVMModFlagBehavior::Warning, diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index e571912973cc..b35ffac91b7e 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -2379,7 +2379,7 @@ fn add_order_independent_options( } // OBJECT-FILES-NO, AUDIT-ORDER - if sess.opts.cg.ehcont_guard { + if sess.opts.unstable_opts.ehcont_guard { cmd.ehcont_guard(); } diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 924bd97b4d54..4e669c81bf32 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1387,8 +1387,6 @@ options! { "allow the linker to link its default libraries (default: no)"), dlltool: Option = (None, parse_opt_pathbuf, [UNTRACKED], "import library generation tool (ignored except when targeting windows-gnu)"), - ehcont_guard: bool = (false, parse_bool, [TRACKED], - "generate Windows EHCont Guard tables"), embed_bitcode: bool = (true, parse_bool, [TRACKED], "emit bitcode in rlibs (default: yes)"), extra_filename: String = (String::new(), parse_string, [UNTRACKED], @@ -1584,6 +1582,8 @@ options! { "version of DWARF debug information to emit (default: 2 or 4, depending on platform)"), dylib_lto: bool = (false, parse_bool, [UNTRACKED], "enables LTO for dylib crate type"), + ehcont_guard: bool = (false, parse_bool, [TRACKED], + "generate Windows EHCont Guard tables"), emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED], "emit a section containing stack size metadata (default: no)"), emit_thin_lto: bool = (true, parse_bool, [TRACKED], diff --git a/tests/codegen/ehcontguard_enabled.rs b/tests/codegen/ehcontguard_enabled.rs index 5e7ea90940e7..03aaa342b967 100644 --- a/tests/codegen/ehcontguard_enabled.rs +++ b/tests/codegen/ehcontguard_enabled.rs @@ -1,4 +1,4 @@ -// compile-flags: -C ehcont_guard +// compile-flags: -Z ehcont-guard #![crate_type = "lib"] From 80896cbe351aa31ddc2f805c71e7eff85495d902 Mon Sep 17 00:00:00 2001 From: Arlie Davis Date: Tue, 21 Nov 2023 14:35:02 -0800 Subject: [PATCH 33/66] update -Cehcont-guard and comment --- src/bootstrap/src/core/builder.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/src/core/builder.rs b/src/bootstrap/src/core/builder.rs index 5fd0d6a50ca6..507306fd274c 100644 --- a/src/bootstrap/src/core/builder.rs +++ b/src/bootstrap/src/core/builder.rs @@ -1964,10 +1964,14 @@ impl<'a> Builder<'a> { rustflags.arg("-Ccontrol-flow-guard"); } - // Same for EHCont Guard (this is not combined with the previous if-statement to make - // merges with upstream easier). + // If EHCont Guard is enabled, pass the `-Zehcont-guard` flag to rustc when compiling the + // standard library, since this might be linked into the final outputs produced by rustc. + // Since this mitigation is only available on Windows, only enable it for the standard + // library in case the compiler is run on a non-Windows platform. + // This is not needed for stage 0 artifacts because these will only be used for building + // the stage 1 compiler. if cfg!(windows) && mode == Mode::Std && self.config.ehcont_guard && compiler.stage >= 1 { - rustflags.arg("-Cehcont-guard"); + rustflags.arg("-Zehcont-guard"); } // For `cargo doc` invocations, make rustdoc print the Rust version into the docs From 9fe6bb4a10a51073c01d501a9734efb9e818adad Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 14 Nov 2023 14:00:25 +1100 Subject: [PATCH 34/66] Add some comments. --- compiler/rustc_ast_pretty/src/pprust/state.rs | 5 +++++ compiler/rustc_hir_pretty/src/lib.rs | 3 +++ 2 files changed, 8 insertions(+) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index f29e8b546812..8f6217379a4b 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1,3 +1,7 @@ +//! AST pretty printing. +//! +//! Note that HIR pretty printing is layered on top of this crate. + mod expr; mod item; @@ -256,6 +260,7 @@ impl std::ops::DerefMut for State<'_> { } } +/// This trait is used for both AST and HIR pretty-printing. pub trait PrintState<'a>: std::ops::Deref + std::ops::DerefMut { fn comments(&mut self) -> &mut Option>; fn ann_post(&mut self, ident: Ident); diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index a1a218a421b8..9f7d7f989e33 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -1,3 +1,6 @@ +//! HIR pretty-printing is layered on top of AST pretty-printing. A number of +//! the definitions in this file have equivalents in `rustc_ast_pretty`. + #![recursion_limit = "256"] #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] From 6686221d296128cdc55c2ee48420ce4a8d82f0c0 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 15 Nov 2023 13:38:47 +1100 Subject: [PATCH 35/66] Remove outdated reference to compiler plugins. --- compiler/rustc_interface/src/passes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 0baf77c4f7e1..9cec1004f9de 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -114,7 +114,7 @@ impl LintStoreExpand for LintStoreExpandImpl<'_> { } } -/// Runs the "early phases" of the compiler: initial `cfg` processing, loading compiler plugins, +/// Runs the "early phases" of the compiler: initial `cfg` processing, /// syntax expansion, secondary `cfg` expansion, synthesis of a test /// harness if one is to be provided, injection of a dependency on the /// standard library and prelude, and name resolution. From ad12be3668de26dc1b35bb374e93b2bab58d02ae Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 22:59:02 +0000 Subject: [PATCH 36/66] allow clippy style in windows/c.rs We intentional use the Windows API style here. --- library/std/src/sys/windows/c.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/library/std/src/sys/windows/c.rs b/library/std/src/sys/windows/c.rs index a349e24b0395..ede04abf105f 100644 --- a/library/std/src/sys/windows/c.rs +++ b/library/std/src/sys/windows/c.rs @@ -3,6 +3,7 @@ #![allow(nonstandard_style)] #![cfg_attr(test, allow(dead_code))] #![unstable(issue = "none", feature = "windows_c")] +#![allow(clippy::style)] use crate::ffi::CStr; use crate::mem; From cf561904dbf4c2d8be6547b827af3a7387212580 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 20 Nov 2023 13:12:07 +1100 Subject: [PATCH 37/66] Add comments about a timer. --- compiler/rustc_interface/src/queries.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 3fee2d289818..416ffeba4c7b 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -304,6 +304,7 @@ impl Compiler { where F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T, { + // Must declare `_timer` first so that it is dropped after `queries`. let mut _timer = None; let queries = Queries::new(self); let ret = f(&queries); @@ -324,6 +325,8 @@ impl Compiler { .time("serialize_dep_graph", || gcx.enter(rustc_incremental::save_dep_graph)); } + // The timer's lifetime spans the dropping of `queries`, which contains + // the global context. _timer = Some(self.session().timer("free_global_ctxt")); ret From 09c807ed829b58a67a4e4612279b5832d969b9fa Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 20 Nov 2023 14:13:52 +1100 Subject: [PATCH 38/66] Add two useful comments. --- compiler/rustc_driver_impl/src/lib.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 6ee7213a19d8..1a59d72b441e 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -455,6 +455,8 @@ fn run_compiler( let ongoing_codegen = queries.ongoing_codegen()?; + // This must run after monomorphization so that all generic types + // have been instantiated. if sess.opts.unstable_opts.print_type_sizes { sess.code_stats.print_type_sizes(); } @@ -469,6 +471,8 @@ fn run_compiler( Ok(Some(linker)) })?; + // Linking is done outside the `compiler.enter()` so that the + // `GlobalCtxt` within `Queries` can be freed as early as possible. if let Some(linker) = linker { let _timer = sess.timer("link"); linker.link(sess, codegen_backend)? From 3a4798c92d5ea9e4a3a0e6d4e2b597b0e9c7cf9a Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 20 Nov 2023 13:26:09 +1100 Subject: [PATCH 39/66] Make `Compiler::{sess,codegen_backend}` public. And remove the relevant getters on `Compiler` and `Queries`. --- compiler/rustc_driver_impl/src/lib.rs | 6 ++-- compiler/rustc_interface/src/interface.rs | 10 ++---- compiler/rustc_interface/src/passes.rs | 4 +-- compiler/rustc_interface/src/queries.rs | 35 ++++++++----------- src/librustdoc/doctest.rs | 8 ++--- src/librustdoc/lib.rs | 2 +- tests/run-make-fulldeps/issue-19371/foo.rs | 2 +- .../obtain-borrowck/driver.rs | 2 +- 8 files changed, 28 insertions(+), 41 deletions(-) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 1a59d72b441e..19730e81c85b 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -360,8 +360,8 @@ fn run_compiler( drop(default_handler); interface::run_compiler(config, |compiler| { - let sess = compiler.session(); - let codegen_backend = compiler.codegen_backend(); + let sess = &compiler.sess; + let codegen_backend = &*compiler.codegen_backend; // This implements `-Whelp`. It should be handled very early, like // `--help`/`-Zhelp`/`-Chelp`. This is the earliest it can run, because @@ -672,7 +672,7 @@ fn process_rlink(sess: &Session, compiler: &interface::Compiler) { }; } }; - let result = compiler.codegen_backend().link(sess, codegen_results, &outputs); + let result = compiler.codegen_backend.link(sess, codegen_results, &outputs); abort_on_err(result, sess); } else { sess.emit_fatal(RlinkNotAFile {}) diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index 6225424fe4ac..91fd4b4a1d0f 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -38,18 +38,12 @@ pub type Result = result::Result; /// Can be used to run `rustc_interface` queries. /// Created by passing [`Config`] to [`run_compiler`]. pub struct Compiler { - sess: Session, - codegen_backend: Box, + pub sess: Session, + pub codegen_backend: Box, pub(crate) override_queries: Option, } impl Compiler { - pub fn session(&self) -> &Session { - &self.sess - } - pub fn codegen_backend(&self) -> &dyn CodegenBackend { - &*self.codegen_backend - } pub fn build_output_filenames( &self, sess: &Session, diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index ec024dac8ddb..5250dbc79067 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -645,10 +645,10 @@ pub fn create_global_ctxt<'tcx>( // incr. comp. yet. dep_graph.assert_ignored(); - let sess = &compiler.session(); + let sess = &compiler.sess; let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess); - let codegen_backend = compiler.codegen_backend(); + let codegen_backend = &compiler.codegen_backend; let mut providers = *DEFAULT_QUERY_PROVIDERS; codegen_backend.provide(&mut providers); diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 416ffeba4c7b..9fb9778cd562 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -17,7 +17,8 @@ use rustc_middle::dep_graph::DepGraph; use rustc_middle::ty::{GlobalCtxt, TyCtxt}; use rustc_session::config::{self, CrateType, OutputFilenames, OutputType}; use rustc_session::cstore::Untracked; -use rustc_session::{output::find_crate_name, Session}; +use rustc_session::output::find_crate_name; +use rustc_session::Session; use rustc_span::symbol::sym; use std::any::Any; use std::cell::{RefCell, RefMut}; @@ -101,17 +102,10 @@ impl<'tcx> Queries<'tcx> { } } - fn session(&self) -> &Session { - self.compiler.session() - } - - fn codegen_backend(&self) -> &dyn CodegenBackend { - self.compiler.codegen_backend() - } - pub fn parse(&self) -> Result> { - self.parse - .compute(|| passes::parse(self.session()).map_err(|mut parse_error| parse_error.emit())) + self.parse.compute(|| { + passes::parse(&self.compiler.sess).map_err(|mut parse_error| parse_error.emit()) + }) } #[deprecated = "pre_configure may be made private in the future. If you need it please open an issue with your use case."] @@ -119,7 +113,7 @@ impl<'tcx> Queries<'tcx> { self.pre_configure.compute(|| { let mut krate = self.parse()?.steal(); - let sess = self.session(); + let sess = &self.compiler.sess; rustc_builtin_macros::cmdline_attrs::inject( &mut krate, &sess.parse_sess, @@ -134,7 +128,7 @@ impl<'tcx> Queries<'tcx> { pub fn global_ctxt(&'tcx self) -> Result>> { self.gcx.compute(|| { - let sess = self.session(); + let sess = &self.compiler.sess; #[allow(deprecated)] let (krate, pre_configured_attrs) = self.pre_configure()?.steal(); @@ -150,7 +144,7 @@ impl<'tcx> Queries<'tcx> { let dep_graph = setup_dep_graph(sess, crate_name, stable_crate_id)?; let cstore = FreezeLock::new(Box::new(CStore::new( - self.codegen_backend().metadata_loader(), + self.compiler.codegen_backend.metadata_loader(), stable_crate_id, )) as _); let definitions = FreezeLock::new(Definitions::new(stable_crate_id)); @@ -189,16 +183,16 @@ impl<'tcx> Queries<'tcx> { pub fn ongoing_codegen(&'tcx self) -> Result> { self.global_ctxt()?.enter(|tcx| { // Don't do code generation if there were any errors - self.session().compile_status()?; + self.compiler.sess.compile_status()?; // If we have any delayed bugs, for example because we created TyKind::Error earlier, // it's likely that codegen will only cause more ICEs, obscuring the original problem - self.session().diagnostic().flush_delayed(); + self.compiler.sess.diagnostic().flush_delayed(); // Hook for UI tests. Self::check_for_rustc_errors_attr(tcx); - Ok(passes::start_codegen(self.codegen_backend(), tcx)) + Ok(passes::start_codegen(&*self.compiler.codegen_backend, tcx)) }) } @@ -317,17 +311,16 @@ impl Compiler { // after this point, they'll show up as "" in self-profiling data. { let _prof_timer = - queries.session().prof.generic_activity("self_profile_alloc_query_strings"); + queries.compiler.sess.prof.generic_activity("self_profile_alloc_query_strings"); gcx.enter(rustc_query_impl::alloc_self_profile_query_strings); } - self.session() - .time("serialize_dep_graph", || gcx.enter(rustc_incremental::save_dep_graph)); + self.sess.time("serialize_dep_graph", || gcx.enter(rustc_incremental::save_dep_graph)); } // The timer's lifetime spans the dropping of `queries`, which contains // the global context. - _timer = Some(self.session().timer("free_global_ctxt")); + _timer = Some(self.sess.timer("free_global_ctxt")); ret } diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index e551e37f1819..3a114bcc1856 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -127,17 +127,17 @@ pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> { options, false, opts, - Some(compiler.session().parse_sess.clone_source_map()), + Some(compiler.sess.parse_sess.clone_source_map()), None, enable_per_target_ignores, ); let mut hir_collector = HirCollector { - sess: compiler.session(), + sess: &compiler.sess, collector: &mut collector, map: tcx.hir(), codes: ErrorCodes::from( - compiler.session().opts.unstable_features.is_nightly_build(), + compiler.sess.opts.unstable_features.is_nightly_build(), ), tcx, }; @@ -150,7 +150,7 @@ pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> { collector }); - if compiler.session().diagnostic().has_errors_or_lint_errors().is_some() { + if compiler.sess.diagnostic().has_errors_or_lint_errors().is_some() { FatalError.raise(); } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 5144bbdaf5e1..1c02e0ba76ec 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -794,7 +794,7 @@ fn main_args( let config = core::create_config(options, &render_options, using_internal_features); interface::run_compiler(config, |compiler| { - let sess = compiler.session(); + let sess = &compiler.sess; if sess.opts.describe_lints { rustc_driver::describe_lints(sess); diff --git a/tests/run-make-fulldeps/issue-19371/foo.rs b/tests/run-make-fulldeps/issue-19371/foo.rs index 9be0fdccebec..e46aef9ea89c 100644 --- a/tests/run-make-fulldeps/issue-19371/foo.rs +++ b/tests/run-make-fulldeps/issue-19371/foo.rs @@ -72,6 +72,6 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) { let ongoing_codegen = queries.ongoing_codegen()?; queries.linker(ongoing_codegen) }); - linker.unwrap().link(compiler.session(), compiler.codegen_backend()).unwrap(); + linker.unwrap().link(&compiler.sess, &*compiler.codegen_backend).unwrap(); }); } diff --git a/tests/run-make-fulldeps/obtain-borrowck/driver.rs b/tests/run-make-fulldeps/obtain-borrowck/driver.rs index 5df4c558ee17..9cbe9e5900ab 100644 --- a/tests/run-make-fulldeps/obtain-borrowck/driver.rs +++ b/tests/run-make-fulldeps/obtain-borrowck/driver.rs @@ -61,7 +61,7 @@ impl rustc_driver::Callbacks for CompilerCalls { compiler: &Compiler, queries: &'tcx Queries<'tcx>, ) -> Compilation { - compiler.session().abort_if_errors(); + compiler.sess.abort_if_errors(); queries.global_ctxt().unwrap().enter(|tcx| { // Collect definition ids of MIR bodies. let hir = tcx.hir(); From 971010ea5a8635dc55ad436c785bb1efe3a67cdd Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 20 Nov 2023 15:09:05 +1100 Subject: [PATCH 40/66] Merge `Queries::{ongoing_codegen,linker}`. There is no real need for them to be separate. --- compiler/rustc_driver_impl/src/lib.rs | 3 +-- compiler/rustc_interface/src/queries.rs | 30 ++++++++++------------ tests/run-make-fulldeps/issue-19371/foo.rs | 3 +-- 3 files changed, 15 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 19730e81c85b..5ab14fbc6874 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -453,7 +453,7 @@ fn run_compiler( return early_exit(); } - let ongoing_codegen = queries.ongoing_codegen()?; + let linker = queries.codegen_and_build_linker()?; // This must run after monomorphization so that all generic types // have been instantiated. @@ -467,7 +467,6 @@ fn run_compiler( sess.code_stats.print_vtable_sizes(crate_name); } - let linker = queries.linker(ongoing_codegen)?; Ok(Some(linker)) })?; diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 9fb9778cd562..1c65cf19cde3 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -180,22 +180,6 @@ impl<'tcx> Queries<'tcx> { }) } - pub fn ongoing_codegen(&'tcx self) -> Result> { - self.global_ctxt()?.enter(|tcx| { - // Don't do code generation if there were any errors - self.compiler.sess.compile_status()?; - - // If we have any delayed bugs, for example because we created TyKind::Error earlier, - // it's likely that codegen will only cause more ICEs, obscuring the original problem - self.compiler.sess.diagnostic().flush_delayed(); - - // Hook for UI tests. - Self::check_for_rustc_errors_attr(tcx); - - Ok(passes::start_codegen(&*self.compiler.codegen_backend, tcx)) - }) - } - /// Check for the `#[rustc_error]` annotation, which forces an error in codegen. This is used /// to write UI tests that actually test that compilation succeeds without reporting /// an error. @@ -230,8 +214,20 @@ impl<'tcx> Queries<'tcx> { } } - pub fn linker(&'tcx self, ongoing_codegen: Box) -> Result { + pub fn codegen_and_build_linker(&'tcx self) -> Result { self.global_ctxt()?.enter(|tcx| { + // Don't do code generation if there were any errors + self.compiler.sess.compile_status()?; + + // If we have any delayed bugs, for example because we created TyKind::Error earlier, + // it's likely that codegen will only cause more ICEs, obscuring the original problem + self.compiler.sess.diagnostic().flush_delayed(); + + // Hook for UI tests. + Self::check_for_rustc_errors_attr(tcx); + + let ongoing_codegen = passes::start_codegen(&*self.compiler.codegen_backend, tcx); + Ok(Linker { dep_graph: tcx.dep_graph.clone(), output_filenames: tcx.output_filenames(()).clone(), diff --git a/tests/run-make-fulldeps/issue-19371/foo.rs b/tests/run-make-fulldeps/issue-19371/foo.rs index e46aef9ea89c..a0bbe3851e82 100644 --- a/tests/run-make-fulldeps/issue-19371/foo.rs +++ b/tests/run-make-fulldeps/issue-19371/foo.rs @@ -69,8 +69,7 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) { interface::run_compiler(config, |compiler| { let linker = compiler.enter(|queries| { queries.global_ctxt()?.enter(|tcx| tcx.analysis(()))?; - let ongoing_codegen = queries.ongoing_codegen()?; - queries.linker(ongoing_codegen) + queries.codegen_and_build_linker() }); linker.unwrap().link(&compiler.sess, &*compiler.codegen_backend).unwrap(); }); From fa5ff859e610b46b924ac17df63de69c734759f8 Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Tue, 7 Nov 2023 14:12:58 -0800 Subject: [PATCH 41/66] Add support to global allocation to stable-mir --- .../rustc_smir/src/rustc_internal/internal.rs | 3 +- compiler/rustc_smir/src/rustc_internal/mod.rs | 2 +- compiler/rustc_smir/src/rustc_smir/mod.rs | 73 +++++++++++++++++-- compiler/stable_mir/src/lib.rs | 30 ++++---- compiler/stable_mir/src/mir.rs | 1 + compiler/stable_mir/src/mir/alloc.rs | 37 ++++++++++ compiler/stable_mir/src/mir/mono.rs | 25 ++++++- compiler/stable_mir/src/ty.rs | 3 +- 8 files changed, 150 insertions(+), 24 deletions(-) create mode 100644 compiler/stable_mir/src/mir/alloc.rs diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index 24b1a3c63be6..988d1d7226a1 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -7,12 +7,13 @@ use crate::rustc_smir::Tables; use rustc_middle::ty::{self as rustc_ty, Ty as InternalTy}; use rustc_span::Symbol; +use stable_mir::mir::alloc::AllocId; use stable_mir::mir::mono::{Instance, MonoItem, StaticDef}; use stable_mir::ty::{ AdtDef, Binder, BoundRegionKind, BoundTyKind, BoundVariableKind, ClosureKind, Const, FloatTy, GenericArgKind, GenericArgs, IntTy, Region, RigidTy, TraitRef, Ty, UintTy, }; -use stable_mir::{AllocId, CrateItem, DefId}; +use stable_mir::{CrateItem, DefId}; use super::RustcInternal; diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs index fa75fd3076ce..b37c9a1f632e 100644 --- a/compiler/rustc_smir/src/rustc_internal/mod.rs +++ b/compiler/rustc_smir/src/rustc_internal/mod.rs @@ -118,7 +118,7 @@ impl<'tcx> Tables<'tcx> { self.def_ids.create_or_fetch(did) } - fn create_alloc_id(&mut self, aid: AllocId) -> stable_mir::AllocId { + fn create_alloc_id(&mut self, aid: AllocId) -> stable_mir::mir::alloc::AllocId { self.alloc_ids.create_or_fetch(aid) } diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 2a9f0b426784..509706387db6 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -17,15 +17,16 @@ use rustc_middle::mir::mono::MonoItem; use rustc_middle::ty::{self, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, Variance}; use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_target::abi::FieldIdx; -use stable_mir::mir::mono::InstanceDef; +use stable_mir::mir::alloc::GlobalAlloc; +use stable_mir::mir::mono::{InstanceDef, StaticDef}; use stable_mir::mir::{ Body, ConstOperand, CopyNonOverlapping, Statement, UserTypeProjection, VarDebugInfoFragment, VariantIdx, }; use stable_mir::ty::{ - AdtDef, AdtKind, ClosureDef, ClosureKind, Const, ConstId, ConstantKind, EarlyParamRegion, - FloatTy, FnDef, GenericArgs, GenericParamDef, IntTy, LineInfo, Movability, RigidTy, Span, - TyKind, UintTy, + AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, ConstId, ConstantKind, + EarlyParamRegion, FloatTy, FnDef, GenericArgs, GenericParamDef, IntTy, LineInfo, Movability, + RigidTy, Span, TyKind, UintTy, }; use stable_mir::{self, opaque, Context, CrateItem, Error, Filename, ItemKind}; use std::cell::RefCell; @@ -318,6 +319,18 @@ impl<'tcx> Context for TablesWrapper<'tcx> { .ok_or_else(|| Error::new(format!("Const `{cnst:?}` cannot be encoded as u64"))) } + fn eval_static_initializer(&self, def: StaticDef) -> Result { + let mut tables = self.0.borrow_mut(); + let def_id = def.0.internal(&mut *tables); + tables.tcx.eval_static_initializer(def_id).stable(&mut *tables) + } + + fn global_alloc(&self, alloc: stable_mir::mir::alloc::AllocId) -> GlobalAlloc { + let mut tables = self.0.borrow_mut(); + let alloc_id = alloc.internal(&mut *tables); + tables.tcx.global_alloc(alloc_id).stable(&mut *tables) + } + fn usize_to_const(&self, val: u64) -> Result { let mut tables = self.0.borrow_mut(); let ty = tables.tcx.types.usize; @@ -342,7 +355,7 @@ pub(crate) struct TablesWrapper<'tcx>(pub(crate) RefCell>); pub struct Tables<'tcx> { pub(crate) tcx: TyCtxt<'tcx>, pub(crate) def_ids: IndexMap, - pub(crate) alloc_ids: IndexMap, + pub(crate) alloc_ids: IndexMap, pub(crate) spans: IndexMap, pub(crate) types: IndexMap, stable_mir::ty::Ty>, pub(crate) instances: IndexMap, InstanceDef>, @@ -1590,6 +1603,14 @@ impl<'tcx> Stable<'tcx> for ty::BoundTy { } } +impl<'tcx> Stable<'tcx> for mir::interpret::ConstAllocation<'tcx> { + type T = Allocation; + + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + self.inner().stable(tables) + } +} + impl<'tcx> Stable<'tcx> for mir::interpret::Allocation { type T = stable_mir::ty::Allocation; @@ -1602,6 +1623,25 @@ impl<'tcx> Stable<'tcx> for mir::interpret::Allocation { } } +impl<'tcx> Stable<'tcx> for mir::interpret::GlobalAlloc<'tcx> { + type T = GlobalAlloc; + + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + match self { + mir::interpret::GlobalAlloc::Function(instance) => { + GlobalAlloc::Function(instance.stable(tables)) + } + mir::interpret::GlobalAlloc::VTable(ty, trait_ref) => { + GlobalAlloc::VTable(ty.stable(tables), trait_ref.stable(tables)) + } + mir::interpret::GlobalAlloc::Static(def) => { + GlobalAlloc::Static(tables.static_def(*def)) + } + mir::interpret::GlobalAlloc::Memory(alloc) => GlobalAlloc::Memory(alloc.stable(tables)), + } + } +} + impl<'tcx> Stable<'tcx> for ty::trait_def::TraitSpecializationKind { type T = stable_mir::ty::TraitSpecializationKind; fn stable(&self, _: &mut Tables<'tcx>) -> Self::T { @@ -1989,6 +2029,14 @@ impl<'tcx> Stable<'tcx> for MonoItem<'tcx> { } } +impl<'tcx> Stable<'tcx> for mir::interpret::ErrorHandled { + type T = Error; + + fn stable(&self, _tables: &mut Tables<'tcx>) -> Self::T { + Error::new(format!("{self:?}")) + } +} + impl<'tcx, T> Stable<'tcx> for &T where T: Stable<'tcx>, @@ -2010,3 +2058,18 @@ where self.as_ref().map(|value| value.stable(tables)) } } + +impl<'tcx, T, E> Stable<'tcx> for Result +where + T: Stable<'tcx>, + E: Stable<'tcx>, +{ + type T = Result; + + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + match self { + Ok(val) => Ok(val.stable(tables)), + Err(error) => Err(error.stable(tables)), + } + } +} diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs index 5eb6a8a5e543..d5c4881c89d2 100644 --- a/compiler/stable_mir/src/lib.rs +++ b/compiler/stable_mir/src/lib.rs @@ -17,7 +17,7 @@ //! The goal is to eventually be published on //! [crates.io](https://crates.io). -use crate::mir::mono::InstanceDef; +use crate::mir::mono::{InstanceDef, StaticDef}; use crate::mir::Body; use std::fmt; use std::fmt::Debug; @@ -37,9 +37,10 @@ pub mod mir; pub mod ty; pub mod visitor; +use crate::mir::alloc::{AllocId, GlobalAlloc}; use crate::mir::pretty::function_name; use crate::mir::Mutability; -use crate::ty::{AdtDef, AdtKind, ClosureDef, ClosureKind, Const, RigidTy}; +use crate::ty::{AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, RigidTy}; pub use error::*; use mir::mono::Instance; use ty::{FnDef, GenericArgs}; @@ -73,19 +74,6 @@ impl IndexedVal for DefId { } } -/// A unique identification number for each provenance -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub struct AllocId(usize); - -impl IndexedVal for AllocId { - fn to_val(index: usize) -> Self { - AllocId(index) - } - fn to_index(&self) -> usize { - self.0 - } -} - /// A list of crate items. pub type CrateItems = Vec; @@ -141,6 +129,10 @@ impl CrateItem { with(|cx| cx.def_ty(self.0)) } + pub fn is_foreign_item(&self) -> bool { + with(|cx| cx.is_foreign_item(*self)) + } + pub fn dump(&self, w: &mut W) -> io::Result<()> { writeln!(w, "{}", function_name(*self))?; self.body().dump(w) @@ -190,6 +182,8 @@ pub fn trait_impl(trait_impl: &ImplDef) -> ImplTrait { with(|cx| cx.trait_impl(trait_impl)) } +/// This trait defines the interface between stable_mir and the Rust compiler. +/// Do not use this directly. pub trait Context { fn entry_fn(&self) -> Option; /// Retrieve all items of the local crate that have a MIR associated with them. @@ -291,6 +285,12 @@ pub trait Context { args: &GenericArgs, kind: ClosureKind, ) -> Option; + + /// Evaluate a static's initializer. + fn eval_static_initializer(&self, def: StaticDef) -> Result; + + /// Retrieve global allocation for the given allocation ID. + fn global_alloc(&self, id: AllocId) -> GlobalAlloc; } // A thread local variable that stores a pointer to the tables mapping between TyCtxt diff --git a/compiler/stable_mir/src/mir.rs b/compiler/stable_mir/src/mir.rs index 2cbe6eb4ad11..82555461d644 100644 --- a/compiler/stable_mir/src/mir.rs +++ b/compiler/stable_mir/src/mir.rs @@ -1,3 +1,4 @@ +pub mod alloc; mod body; pub mod mono; pub mod pretty; diff --git a/compiler/stable_mir/src/mir/alloc.rs b/compiler/stable_mir/src/mir/alloc.rs new file mode 100644 index 000000000000..ca24653585ce --- /dev/null +++ b/compiler/stable_mir/src/mir/alloc.rs @@ -0,0 +1,37 @@ +use crate::mir::mono::{Instance, StaticDef}; +use crate::ty::{Allocation, Binder, ExistentialTraitRef, IndexedVal, Ty}; +use crate::with; + +/// An allocation in the SMIR global memory can be either a function pointer, +/// a static, or a "real" allocation with some data in it. +#[derive(Debug, Clone, Eq, PartialEq)] +pub enum GlobalAlloc { + /// The alloc ID is used as a function pointer. + Function(Instance), + /// This alloc ID points to a symbolic (not-reified) vtable. + VTable(Ty, Option>), + /// The alloc ID points to a "lazy" static variable that did not get computed (yet). + /// This is also used to break the cycle in recursive statics. + Static(StaticDef), + /// The alloc ID points to memory. + Memory(Allocation), +} + +impl From for GlobalAlloc { + fn from(value: AllocId) -> Self { + with(|cx| cx.global_alloc(value)) + } +} + +/// A unique identification number for each provenance +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct AllocId(usize); + +impl IndexedVal for AllocId { + fn to_val(index: usize) -> Self { + AllocId(index) + } + fn to_index(&self) -> usize { + self.0 + } +} diff --git a/compiler/stable_mir/src/mir/mono.rs b/compiler/stable_mir/src/mir/mono.rs index 8c43f2c4b8f2..9cec963cf849 100644 --- a/compiler/stable_mir/src/mir/mono.rs +++ b/compiler/stable_mir/src/mir/mono.rs @@ -1,5 +1,5 @@ use crate::mir::Body; -use crate::ty::{ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty}; +use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty}; use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque}; use std::fmt::{Debug, Formatter}; @@ -37,6 +37,11 @@ impl Instance { with(|context| context.instance_body(self.def)) } + pub fn is_foreign_item(&self) -> bool { + let item = CrateItem::try_from(*self); + item.as_ref().map_or(false, CrateItem::is_foreign_item) + } + /// Get the instance type with generic substitutions applied and lifetimes erased. pub fn ty(&self) -> Ty { with(|context| context.instance_ty(self.def)) @@ -128,6 +133,18 @@ impl From for MonoItem { } } +impl From for MonoItem { + fn from(value: StaticDef) -> Self { + MonoItem::Static(value) + } +} + +impl From for CrateItem { + fn from(value: StaticDef) -> Self { + CrateItem(value.0) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InstanceDef(usize); @@ -147,9 +164,15 @@ impl TryFrom for StaticDef { } impl StaticDef { + /// Return the type of this static definition. pub fn ty(&self) -> Ty { with(|cx| cx.def_ty(self.0)) } + + /// Evaluate a static's initializer, returning the allocation of the initializer's memory. + pub fn eval_initializer(&self) -> Result { + with(|cx| cx.eval_static_initializer(*self)) + } } impl IndexedVal for InstanceDef { diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index abe6f8ec12f1..010e2e7e4a69 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -1,8 +1,9 @@ use super::{ mir::Safety, mir::{Body, Mutability}, - with, AllocId, DefId, Error, Symbol, + with, DefId, Error, Symbol, }; +use crate::mir::alloc::AllocId; use crate::{Filename, Opaque}; use std::fmt::{self, Debug, Display, Formatter}; From 5b3cf6610b7c94d5eea715386946ba0bf564690e Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Fri, 17 Nov 2023 08:05:40 -0800 Subject: [PATCH 42/66] Add support to get virtual table allocation --- .../rustc_smir/src/rustc_internal/internal.rs | 26 +++++++++++++++++-- compiler/rustc_smir/src/rustc_internal/mod.rs | 2 +- compiler/rustc_smir/src/rustc_smir/mod.rs | 19 ++++++++++++++ compiler/stable_mir/src/lib.rs | 3 +++ compiler/stable_mir/src/mir/alloc.rs | 7 +++++ 5 files changed, 54 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index 988d1d7226a1..fe226ef60ed4 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -10,8 +10,9 @@ use rustc_span::Symbol; use stable_mir::mir::alloc::AllocId; use stable_mir::mir::mono::{Instance, MonoItem, StaticDef}; use stable_mir::ty::{ - AdtDef, Binder, BoundRegionKind, BoundTyKind, BoundVariableKind, ClosureKind, Const, FloatTy, - GenericArgKind, GenericArgs, IntTy, Region, RigidTy, TraitRef, Ty, UintTy, + AdtDef, Binder, BoundRegionKind, BoundTyKind, BoundVariableKind, ClosureKind, Const, + ExistentialTraitRef, FloatTy, GenericArgKind, GenericArgs, IntTy, Region, RigidTy, TraitRef, + Ty, UintTy, }; use stable_mir::{CrateItem, DefId}; @@ -229,6 +230,17 @@ impl<'tcx> RustcInternal<'tcx> for BoundVariableKind { } } +impl<'tcx> RustcInternal<'tcx> for ExistentialTraitRef { + type T = rustc_ty::ExistentialTraitRef<'tcx>; + + fn internal(&self, tables: &mut Tables<'tcx>) -> Self::T { + rustc_ty::ExistentialTraitRef { + def_id: self.def_id.0.internal(tables), + args: self.generic_args.internal(tables), + } + } +} + impl<'tcx> RustcInternal<'tcx> for TraitRef { type T = rustc_ty::TraitRef<'tcx>; @@ -277,3 +289,13 @@ where (*self).internal(tables) } } +impl<'tcx, T> RustcInternal<'tcx> for Option +where + T: RustcInternal<'tcx>, +{ + type T = Option; + + fn internal(&self, tables: &mut Tables<'tcx>) -> Self::T { + self.as_ref().map(|inner| inner.internal(tables)) + } +} diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs index b37c9a1f632e..fed21f16a4e5 100644 --- a/compiler/rustc_smir/src/rustc_internal/mod.rs +++ b/compiler/rustc_smir/src/rustc_internal/mod.rs @@ -118,7 +118,7 @@ impl<'tcx> Tables<'tcx> { self.def_ids.create_or_fetch(did) } - fn create_alloc_id(&mut self, aid: AllocId) -> stable_mir::mir::alloc::AllocId { + pub(crate) fn create_alloc_id(&mut self, aid: AllocId) -> stable_mir::mir::alloc::AllocId { self.alloc_ids.create_or_fetch(aid) } diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 509706387db6..403c7703debc 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -331,6 +331,18 @@ impl<'tcx> Context for TablesWrapper<'tcx> { tables.tcx.global_alloc(alloc_id).stable(&mut *tables) } + fn vtable_allocation( + &self, + global_alloc: &GlobalAlloc, + ) -> Option { + let mut tables = self.0.borrow_mut(); + let GlobalAlloc::VTable(ty, trait_ref) = global_alloc else { return None }; + let alloc_id = tables + .tcx + .vtable_allocation((ty.internal(&mut *tables), trait_ref.internal(&mut *tables))); + Some(alloc_id.stable(&mut *tables)) + } + fn usize_to_const(&self, val: u64) -> Result { let mut tables = self.0.borrow_mut(); let ty = tables.tcx.types.usize; @@ -1623,6 +1635,13 @@ impl<'tcx> Stable<'tcx> for mir::interpret::Allocation { } } +impl<'tcx> Stable<'tcx> for mir::interpret::AllocId { + type T = stable_mir::mir::alloc::AllocId; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + tables.create_alloc_id(*self) + } +} + impl<'tcx> Stable<'tcx> for mir::interpret::GlobalAlloc<'tcx> { type T = GlobalAlloc; diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs index d5c4881c89d2..6c1b723a8dae 100644 --- a/compiler/stable_mir/src/lib.rs +++ b/compiler/stable_mir/src/lib.rs @@ -291,6 +291,9 @@ pub trait Context { /// Retrieve global allocation for the given allocation ID. fn global_alloc(&self, id: AllocId) -> GlobalAlloc; + + /// Retrieve the id for the virtual table. + fn vtable_allocation(&self, global_alloc: &GlobalAlloc) -> Option; } // A thread local variable that stores a pointer to the tables mapping between TyCtxt diff --git a/compiler/stable_mir/src/mir/alloc.rs b/compiler/stable_mir/src/mir/alloc.rs index ca24653585ce..ef9053b78ec1 100644 --- a/compiler/stable_mir/src/mir/alloc.rs +++ b/compiler/stable_mir/src/mir/alloc.rs @@ -9,6 +9,7 @@ pub enum GlobalAlloc { /// The alloc ID is used as a function pointer. Function(Instance), /// This alloc ID points to a symbolic (not-reified) vtable. + /// The `None` trait ref is used to represent auto traits. VTable(Ty, Option>), /// The alloc ID points to a "lazy" static variable that did not get computed (yet). /// This is also used to break the cycle in recursive statics. @@ -23,6 +24,12 @@ impl From for GlobalAlloc { } } +impl GlobalAlloc { + pub fn vtable_allocation(&self) -> Option { + with(|cx| cx.vtable_allocation(self)) + } +} + /// A unique identification number for each provenance #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct AllocId(usize); From c07a6d5c9a1aa748d2b7493dbeb4374761919876 Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Mon, 20 Nov 2023 11:39:04 -0800 Subject: [PATCH 43/66] Add allocation test and a bit more documentation --- compiler/stable_mir/src/mir/alloc.rs | 7 ++ .../stable-mir/check_allocation.rs | 119 ++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 tests/ui-fulldeps/stable-mir/check_allocation.rs diff --git a/compiler/stable_mir/src/mir/alloc.rs b/compiler/stable_mir/src/mir/alloc.rs index ef9053b78ec1..af951bcef8c1 100644 --- a/compiler/stable_mir/src/mir/alloc.rs +++ b/compiler/stable_mir/src/mir/alloc.rs @@ -1,3 +1,4 @@ +//! This module provides methods to retrieve allocation information, such as static variables. use crate::mir::mono::{Instance, StaticDef}; use crate::ty::{Allocation, Binder, ExistentialTraitRef, IndexedVal, Ty}; use crate::with; @@ -25,6 +26,12 @@ impl From for GlobalAlloc { } impl GlobalAlloc { + /// Retrieve the allocation id for a global allocation if it exists. + /// + /// For `[GlobalAlloc::VTable]`, this will return the allocation for the VTable of the given + /// type for the optional trait if the type implements the trait. + /// + /// This method will always return `None` for allocations other than `[GlobalAlloc::VTable]`. pub fn vtable_allocation(&self) -> Option { with(|cx| cx.vtable_allocation(self)) } diff --git a/tests/ui-fulldeps/stable-mir/check_allocation.rs b/tests/ui-fulldeps/stable-mir/check_allocation.rs new file mode 100644 index 000000000000..e5fb7311c0b8 --- /dev/null +++ b/tests/ui-fulldeps/stable-mir/check_allocation.rs @@ -0,0 +1,119 @@ +// run-pass +//! Test that users are able to use stable mir APIs to retrieve information of global allocations +//! such as `vtable_allocation`. + +// ignore-stage1 +// ignore-cross-compile +// ignore-remote +// ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 +// edition: 2021 + +#![feature(rustc_private)] +#![feature(assert_matches)] +#![feature(control_flow_enum)] +#![feature(ascii_char, ascii_char_variants)] + +extern crate rustc_hir; +extern crate rustc_middle; +#[macro_use] +extern crate rustc_smir; +extern crate rustc_driver; +extern crate rustc_interface; +extern crate stable_mir; + +use rustc_middle::ty::TyCtxt; +use rustc_smir::rustc_internal; +use stable_mir::{CrateItem, CrateItems, ItemKind}; +use stable_mir::mir::alloc::GlobalAlloc; +use stable_mir::mir::mono::StaticDef; +use std::ascii::Char; +use std::assert_matches::assert_matches; +use std::io::Write; +use std::ops::ControlFlow; + +const CRATE_NAME: &str = "input"; + +/// This function uses the Stable MIR APIs to get information about the test crate. +fn test_stable_mir(_tcx: TyCtxt<'_>) -> ControlFlow<()> { + // Find items in the local crate. + let items = stable_mir::all_local_items(); + check_foo(*get_item(&items, (ItemKind::Static, "FOO")).unwrap()); + check_bar(*get_item(&items, (ItemKind::Static, "BAR")).unwrap()); + ControlFlow::Continue(()) +} + +/// Check the allocation data for static `FOO`. +/// +/// ```no_run +/// static FOO: [&str; 2] = ["hi", "there"]; +/// ``` +fn check_foo(item: CrateItem) { + let def = StaticDef::try_from(item).unwrap(); + let alloc = def.eval_initializer().unwrap(); + assert_eq!(alloc.provenance.ptrs.len(), 2); + + let alloc_id_0 = alloc.provenance.ptrs[0].1.0; + assert_matches!(GlobalAlloc::from(alloc_id_0), GlobalAlloc::Memory(..)); + + let alloc_id_1 = alloc.provenance.ptrs[1].1.0; + assert_matches!(GlobalAlloc::from(alloc_id_1), GlobalAlloc::Memory(..)); +} + +/// Check the allocation data for static `BAR`. +/// +/// ```no_run +/// static BAR: &str = "Bar"; +/// ``` +fn check_bar(item: CrateItem) { + let def = StaticDef::try_from(item).unwrap(); + let alloc = def.eval_initializer().unwrap(); + assert_eq!(alloc.provenance.ptrs.len(), 1); + + let alloc_id_0 = alloc.provenance.ptrs[0].1.0; + let GlobalAlloc::Memory(allocation) = GlobalAlloc::from(alloc_id_0) else { unreachable!() }; + assert_eq!(allocation.bytes.len(), 3); + assert_eq!(allocation.bytes[0].unwrap(), Char::CapitalB.to_u8()); + assert_eq!(allocation.bytes[1].unwrap(), Char::SmallA.to_u8()); + assert_eq!(allocation.bytes[2].unwrap(), Char::SmallR.to_u8()); +} + +// Use internal API to find a function in a crate. +fn get_item<'a>( + items: &'a CrateItems, + item: (ItemKind, &str), +) -> Option<&'a stable_mir::CrateItem> { + items.iter().find(|crate_item| { + (item.0 == crate_item.kind()) && crate_item.name() == item.1 + }) +} + +/// This test will generate and analyze a dummy crate using the stable mir. +/// For that, it will first write the dummy crate into a file. +/// Then it will create a `StableMir` using custom arguments and then +/// it will run the compiler. +fn main() { + let path = "alloc_input.rs"; + generate_input(&path).unwrap(); + let args = vec![ + "rustc".to_string(), + "--crate-name".to_string(), + CRATE_NAME.to_string(), + path.to_string(), + ]; + run!(args, tcx, test_stable_mir(tcx)).unwrap(); +} + +fn generate_input(path: &str) -> std::io::Result<()> { + let mut file = std::fs::File::create(path)?; + write!( + file, + r#" + static FOO: [&str; 2] = ["hi", "there"]; + static BAR: &str = "Bar"; + + pub fn main() {{ + println!("{{FOO:?}}! {{BAR}}"); + }}"# + )?; + Ok(()) +} From 4f958a4802c1c29b804db34d53297504da555d02 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 22 Nov 2023 03:43:59 +0000 Subject: [PATCH 44/66] Allow defining opaques in check_coroutine_obligations --- .../rustc_hir_analysis/src/check/check.rs | 22 +++++++++++++++---- compiler/rustc_middle/src/query/mod.rs | 2 +- tests/ui/coroutine/clone-rpit.rs | 17 ++++++++++++++ 3 files changed, 36 insertions(+), 5 deletions(-) create mode 100644 tests/ui/coroutine/clone-rpit.rs diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index e301f0b22ef7..00f636862beb 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -1468,7 +1468,10 @@ fn opaque_type_cycle_error( err.emit() } -pub(super) fn check_coroutine_obligations(tcx: TyCtxt<'_>, def_id: LocalDefId) { +pub(super) fn check_coroutine_obligations( + tcx: TyCtxt<'_>, + def_id: LocalDefId, +) -> Result<(), ErrorGuaranteed> { debug_assert!(matches!(tcx.def_kind(def_id), DefKind::Coroutine)); let typeck = tcx.typeck(def_id); @@ -1482,8 +1485,9 @@ pub(super) fn check_coroutine_obligations(tcx: TyCtxt<'_>, def_id: LocalDefId) { // typeck writeback gives us predicates with their regions erased. // As borrowck already has checked lifetimes, we do not need to do it again. .ignoring_regions() - // Bind opaque types to `def_id` as they should have been checked by borrowck. - .with_opaque_type_inference(DefiningAnchor::Bind(def_id)) + // Bind opaque types to type checking root, as they should have been checked by borrowck, + // but may show up in some cases, like when (root) obligations are stalled in the new solver. + .with_opaque_type_inference(DefiningAnchor::Bind(typeck.hir_owner.def_id)) .build(); let mut fulfillment_cx = >::new(&infcx); @@ -1513,6 +1517,16 @@ pub(super) fn check_coroutine_obligations(tcx: TyCtxt<'_>, def_id: LocalDefId) { let errors = fulfillment_cx.select_all_or_error(&infcx); debug!(?errors); if !errors.is_empty() { - infcx.err_ctxt().report_fulfillment_errors(errors); + return Err(infcx.err_ctxt().report_fulfillment_errors(errors)); } + + // Check that any hidden types found when checking these stalled coroutine obligations + // are valid. + for (key, ty) in infcx.take_opaque_types() { + let hidden_type = infcx.resolve_vars_if_possible(ty.hidden_type); + let key = infcx.resolve_vars_if_possible(key); + sanity_check_found_hidden_type(tcx, key, hidden_type)?; + } + + Ok(()) } diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index cbba990867e0..c982e2a93253 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -567,7 +567,7 @@ rustc_queries! { separate_provide_extern } - query check_coroutine_obligations(key: LocalDefId) { + query check_coroutine_obligations(key: LocalDefId) -> Result<(), ErrorGuaranteed> { desc { |tcx| "verify auto trait bounds for coroutine interior type `{}`", tcx.def_path_str(key) } } diff --git a/tests/ui/coroutine/clone-rpit.rs b/tests/ui/coroutine/clone-rpit.rs new file mode 100644 index 000000000000..e0061e1c6bb3 --- /dev/null +++ b/tests/ui/coroutine/clone-rpit.rs @@ -0,0 +1,17 @@ +// revisions: current next +//[next] compile-flags: -Ztrait-solver=next +// check-pass + +#![feature(coroutines, coroutine_trait, coroutine_clone)] + +// This stalls the goal `{coroutine} <: impl Clone`, since that has a nested goal +// of `{coroutine}: Clone`. That is only known if we can compute the generator +// witness types, which we don't know until after borrowck. When we later check +// the goal for correctness, we want to be able to bind the `impl Clone` opaque. +pub fn foo<'a, 'b>() -> impl Clone { + move |_: ()| { + let () = yield (); + } +} + +fn main() {} From 3ef9d4d0ed608b0493d66ffe8af2755529ce474c Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 21 Nov 2023 16:35:26 +1100 Subject: [PATCH 45/66] Replace `custom_encodable` with `encodable`. By default, `newtype_index!` types get a default `Encodable`/`Decodable` impl. You can opt out of this with `custom_encodable`. Opting out is the opposite to how Rust normally works with autogenerated (derived) impls. This commit inverts the behaviour, replacing `custom_encodable` with `encodable` which opts into the default `Encodable`/`Decodable` impl. Only 23 of the 59 `newtype_index!` occurrences need `encodable`. Even better, there were eight crates with a dependency on `rustc_serialize` just from unused default `Encodable`/`Decodable` impls. This commit removes that dependency from those eight crates. --- Cargo.lock | 8 -------- compiler/rustc_ast/src/ast.rs | 1 - compiler/rustc_ast/src/node_id.rs | 1 + compiler/rustc_borrowck/Cargo.toml | 1 - compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs | 2 -- compiler/rustc_hir/src/hir_id.rs | 1 + .../src/coherence/inherent_impls_overlap.rs | 1 - compiler/rustc_hir_typeck/Cargo.toml | 1 - compiler/rustc_index_macros/src/newtype.rs | 6 +++--- compiler/rustc_infer/Cargo.toml | 1 - compiler/rustc_lint/src/levels.rs | 1 - compiler/rustc_middle/src/middle/region.rs | 1 + compiler/rustc_middle/src/mir/coverage.rs | 2 ++ compiler/rustc_middle/src/mir/mod.rs | 4 ++++ compiler/rustc_middle/src/mir/query.rs | 1 + compiler/rustc_middle/src/ty/sty.rs | 1 + compiler/rustc_middle/src/ty/typeck_results.rs | 1 + compiler/rustc_mir_build/Cargo.toml | 1 - compiler/rustc_mir_dataflow/Cargo.toml | 1 - compiler/rustc_mir_transform/Cargo.toml | 1 - compiler/rustc_passes/Cargo.toml | 1 - compiler/rustc_query_system/src/dep_graph/serialized.rs | 1 + compiler/rustc_span/src/def_id.rs | 3 +-- compiler/rustc_span/src/hygiene.rs | 2 -- compiler/rustc_target/src/abi/mod.rs | 2 ++ compiler/rustc_trait_selection/Cargo.toml | 1 - compiler/rustc_type_ir/src/const_kind.rs | 2 ++ compiler/rustc_type_ir/src/lib.rs | 3 +++ compiler/rustc_type_ir/src/ty_kind.rs | 3 +++ 29 files changed, 27 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8d54fe7ef763..8c9b12028f09 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3524,7 +3524,6 @@ dependencies = [ "rustc_macros", "rustc_middle", "rustc_mir_dataflow", - "rustc_serialize", "rustc_session", "rustc_span", "rustc_target", @@ -3935,7 +3934,6 @@ dependencies = [ "rustc_lint", "rustc_macros", "rustc_middle", - "rustc_serialize", "rustc_session", "rustc_span", "rustc_target", @@ -3998,7 +3996,6 @@ dependencies = [ "rustc_index", "rustc_macros", "rustc_middle", - "rustc_serialize", "rustc_span", "rustc_target", "smallvec", @@ -4216,7 +4213,6 @@ dependencies = [ "rustc_infer", "rustc_macros", "rustc_middle", - "rustc_serialize", "rustc_session", "rustc_span", "rustc_target", @@ -4240,7 +4236,6 @@ dependencies = [ "rustc_index", "rustc_macros", "rustc_middle", - "rustc_serialize", "rustc_span", "rustc_target", "smallvec", @@ -4267,7 +4262,6 @@ dependencies = [ "rustc_middle", "rustc_mir_build", "rustc_mir_dataflow", - "rustc_serialize", "rustc_session", "rustc_span", "rustc_target", @@ -4341,7 +4335,6 @@ dependencies = [ "rustc_lexer", "rustc_macros", "rustc_middle", - "rustc_serialize", "rustc_session", "rustc_span", "rustc_target", @@ -4565,7 +4558,6 @@ dependencies = [ "rustc_middle", "rustc_parse_format", "rustc_query_system", - "rustc_serialize", "rustc_session", "rustc_span", "rustc_target", diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index c85ff6f5c445..e311352c93de 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2574,7 +2574,6 @@ pub enum AttrStyle { } rustc_index::newtype_index! { - #[custom_encodable] #[debug_format = "AttrId({})"] pub struct AttrId {} } diff --git a/compiler/rustc_ast/src/node_id.rs b/compiler/rustc_ast/src/node_id.rs index d16741757d1f..48081582fc32 100644 --- a/compiler/rustc_ast/src/node_id.rs +++ b/compiler/rustc_ast/src/node_id.rs @@ -8,6 +8,7 @@ rustc_index::newtype_index! { /// This is later turned into [`DefId`] and `HirId` for the HIR. /// /// [`DefId`]: rustc_span::def_id::DefId + #[encodable] #[debug_format = "NodeId({})"] pub struct NodeId { /// The [`NodeId`] used to represent the root of the crate. diff --git a/compiler/rustc_borrowck/Cargo.toml b/compiler/rustc_borrowck/Cargo.toml index 79ad24273250..714f46270f92 100644 --- a/compiler/rustc_borrowck/Cargo.toml +++ b/compiler/rustc_borrowck/Cargo.toml @@ -19,7 +19,6 @@ rustc_lexer = { path = "../rustc_lexer" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } rustc_mir_dataflow = { path = "../rustc_mir_dataflow" } -rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 4f540de7ae01..f2be6f27ff6f 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -189,8 +189,6 @@ impl GlobalFileTable { } rustc_index::newtype_index! { - // Tell the newtype macro to not generate `Encode`/`Decode` impls. - #[custom_encodable] struct LocalFileId {} } diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index 7b741e8882de..c40a317947c0 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -154,6 +154,7 @@ rustc_index::newtype_index! { /// an "item-like" to something else can be implemented by a `Vec` instead of a /// tree or hash map. #[derive(HashStable_Generic)] + #[encodable] pub struct ItemLocalId {} } diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs index 7205b7a21a82..cbce8c4b8b83 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -198,7 +198,6 @@ impl<'tcx> InherentOverlapChecker<'tcx> { // entire graph when there are many connected regions. rustc_index::newtype_index! { - #[custom_encodable] pub struct RegionId {} } diff --git a/compiler/rustc_hir_typeck/Cargo.toml b/compiler/rustc_hir_typeck/Cargo.toml index 0062889d2445..b0c60304424a 100644 --- a/compiler/rustc_hir_typeck/Cargo.toml +++ b/compiler/rustc_hir_typeck/Cargo.toml @@ -19,7 +19,6 @@ rustc_infer = { path = "../rustc_infer" } rustc_lint = { path = "../rustc_lint" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } -rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } diff --git a/compiler/rustc_index_macros/src/newtype.rs b/compiler/rustc_index_macros/src/newtype.rs index 2a974fd26281..62de5c7c6c16 100644 --- a/compiler/rustc_index_macros/src/newtype.rs +++ b/compiler/rustc_index_macros/src/newtype.rs @@ -22,7 +22,7 @@ impl Parse for Newtype { let mut debug_format: Option = None; let mut max = None; let mut consts = Vec::new(); - let mut encodable = true; + let mut encodable = false; let mut ord = true; let mut gate_rustc_only = quote! {}; let mut gate_rustc_only_cfg = quote! { all() }; @@ -34,8 +34,8 @@ impl Parse for Newtype { gate_rustc_only_cfg = quote! { feature = "nightly" }; false } - "custom_encodable" => { - encodable = false; + "encodable" => { + encodable = true; false } "no_ord_impl" => { diff --git a/compiler/rustc_infer/Cargo.toml b/compiler/rustc_infer/Cargo.toml index 00251a192264..73a02a431dfc 100644 --- a/compiler/rustc_infer/Cargo.toml +++ b/compiler/rustc_infer/Cargo.toml @@ -15,7 +15,6 @@ rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } -rustc_serialize = { path = "../rustc_serialize" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 1281cc9f9203..3fc4f0924430 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -56,7 +56,6 @@ struct LintLevelSets { } rustc_index::newtype_index! { - #[custom_encodable] // we don't need encoding struct LintStackIndex { const COMMAND_LINE = 0; } diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index 9d55295fb66b..a0765770a8f6 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -148,6 +148,7 @@ rustc_index::newtype_index! { /// * The subscope with `first_statement_index == 1` is scope of `c`, /// and thus does not include EXPR_2, but covers the `...`. #[derive(HashStable)] + #[encodable] pub struct FirstStatementIndex {} } diff --git a/compiler/rustc_middle/src/mir/coverage.rs b/compiler/rustc_middle/src/mir/coverage.rs index 08d377a8695f..ccd2cd76ad87 100644 --- a/compiler/rustc_middle/src/mir/coverage.rs +++ b/compiler/rustc_middle/src/mir/coverage.rs @@ -17,6 +17,7 @@ rustc_index::newtype_index! { /// Note that LLVM handles counter IDs as `uint32_t`, so there is no need /// to use a larger representation on the Rust side. #[derive(HashStable)] + #[encodable] #[max = 0xFFFF_FFFF] #[debug_format = "CounterId({})"] pub struct CounterId {} @@ -37,6 +38,7 @@ rustc_index::newtype_index! { /// Note that LLVM handles expression IDs as `uint32_t`, so there is no need /// to use a larger representation on the Rust side. #[derive(HashStable)] + #[encodable] #[max = 0xFFFF_FFFF] #[debug_format = "ExpressionId({})"] pub struct ExpressionId {} diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index d4778cdccf37..4e6f5c3fb4e0 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -736,6 +736,7 @@ impl SourceInfo { rustc_index::newtype_index! { #[derive(HashStable)] + #[encodable] #[debug_format = "_{}"] pub struct Local { const RETURN_PLACE = 0; @@ -1171,6 +1172,7 @@ rustc_index::newtype_index! { /// [`CriticalCallEdges`]: ../../rustc_const_eval/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/ #[derive(HashStable)] + #[encodable] #[debug_format = "bb{}"] pub struct BasicBlock { const START_BLOCK = 0; @@ -1305,6 +1307,7 @@ impl<'tcx> BasicBlockData<'tcx> { rustc_index::newtype_index! { #[derive(HashStable)] + #[encodable] #[debug_format = "scope[{}]"] pub struct SourceScope { const OUTERMOST_SOURCE_SCOPE = 0; @@ -1533,6 +1536,7 @@ impl UserTypeProjection { rustc_index::newtype_index! { #[derive(HashStable)] + #[encodable] #[debug_format = "promoted[{}]"] pub struct Promoted {} } diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index b5dd3010d3a8..4f98c302298e 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -132,6 +132,7 @@ pub struct UnsafetyCheckResult { rustc_index::newtype_index! { #[derive(HashStable)] + #[encodable] #[debug_format = "_{}"] pub struct CoroutineSavedLocal {} } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 6609da492981..f3915f6b4103 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1612,6 +1612,7 @@ impl fmt::Debug for EarlyParamRegion { rustc_index::newtype_index! { /// A **region** (lifetime) **v**ariable **ID**. #[derive(HashStable)] + #[encodable] #[debug_format = "'?{}"] pub struct RegionVid {} } diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 0331546cdd90..4a5c89411daa 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -578,6 +578,7 @@ impl<'a, V> LocalTableInContextMut<'a, V> { rustc_index::newtype_index! { #[derive(HashStable)] + #[encodable] #[debug_format = "UserType({})"] pub struct UserTypeAnnotationIndex { const START_INDEX = 0; diff --git a/compiler/rustc_mir_build/Cargo.toml b/compiler/rustc_mir_build/Cargo.toml index 6dceacd75a54..db5422340523 100644 --- a/compiler/rustc_mir_build/Cargo.toml +++ b/compiler/rustc_mir_build/Cargo.toml @@ -17,7 +17,6 @@ rustc_index = { path = "../rustc_index" } rustc_infer = { path = "../rustc_infer" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } -rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } diff --git a/compiler/rustc_mir_dataflow/Cargo.toml b/compiler/rustc_mir_dataflow/Cargo.toml index 61664eb2a6fb..7199db677c46 100644 --- a/compiler/rustc_mir_dataflow/Cargo.toml +++ b/compiler/rustc_mir_dataflow/Cargo.toml @@ -16,7 +16,6 @@ rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } -rustc_serialize = { path = "../rustc_serialize" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml index ea7f2a413fb7..c2ca0a6bcb84 100644 --- a/compiler/rustc_mir_transform/Cargo.toml +++ b/compiler/rustc_mir_transform/Cargo.toml @@ -20,7 +20,6 @@ rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } rustc_mir_build = { path = "../rustc_mir_build" } rustc_mir_dataflow = { path = "../rustc_mir_dataflow" } -rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } diff --git a/compiler/rustc_passes/Cargo.toml b/compiler/rustc_passes/Cargo.toml index d4cd452e7e2a..80e6c104bd46 100644 --- a/compiler/rustc_passes/Cargo.toml +++ b/compiler/rustc_passes/Cargo.toml @@ -19,7 +19,6 @@ rustc_index = { path = "../rustc_index" } rustc_lexer = { path = "../rustc_lexer" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } -rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index e97ef8072045..a70f4138cfb5 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -54,6 +54,7 @@ use std::marker::PhantomData; // unused so that we can store multiple index types in `CompressedHybridIndex`, // and use those bits to encode which index type it contains. rustc_index::newtype_index! { + #[encodable] #[max = 0x7FFF_FFFF] pub struct SerializedDepNodeIndex {} } diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index 595babc26ae6..595456e6d6a1 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -13,7 +13,6 @@ pub type StableCrateIdMap = indexmap::IndexMap>; rustc_index::newtype_index! { - #[custom_encodable] #[debug_format = "crate{}"] pub struct CrateNum {} } @@ -213,7 +212,6 @@ rustc_index::newtype_index! { /// A DefIndex is an index into the hir-map for a crate, identifying a /// particular definition. It should really be considered an interned /// shorthand for a particular DefPath. - #[custom_encodable] // (only encodable in metadata) #[debug_format = "DefIndex({})"] pub struct DefIndex { /// The crate root is always assigned index 0 by the AST Map code, @@ -222,6 +220,7 @@ rustc_index::newtype_index! { } } +// njn: I don't understand these impl Encodable for DefIndex { default fn encode(&self, _: &mut E) { panic!("cannot encode `DefIndex` with `{}`", std::any::type_name::()); diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 988ff57254c5..8c6600c4e531 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -60,7 +60,6 @@ pub struct SyntaxContextData { rustc_index::newtype_index! { /// A unique ID associated with a macro invocation and expansion. - #[custom_encodable] pub struct ExpnIndex {} } @@ -80,7 +79,6 @@ impl fmt::Debug for ExpnId { rustc_index::newtype_index! { /// A unique ID associated with a macro invocation and expansion. - #[custom_encodable] #[no_ord_impl] #[debug_format = "expn{}"] pub struct LocalExpnId {} diff --git a/compiler/rustc_target/src/abi/mod.rs b/compiler/rustc_target/src/abi/mod.rs index b00567e87c65..c1fbc2980a97 100644 --- a/compiler/rustc_target/src/abi/mod.rs +++ b/compiler/rustc_target/src/abi/mod.rs @@ -42,6 +42,7 @@ rustc_index::newtype_index! { /// `d` is `FieldIdx(1)` in `VariantIdx(1)`, and /// `f` is `FieldIdx(1)` in `VariantIdx(0)`. #[derive(HashStable_Generic)] + #[encodable] pub struct FieldIdx {} } @@ -57,6 +58,7 @@ rustc_index::newtype_index! { /// `struct`s, `tuples`, and `unions`s are considered to have a single variant /// with variant index zero, aka [`FIRST_VARIANT`]. #[derive(HashStable_Generic)] + #[encodable] pub struct VariantIdx { /// Equivalent to `VariantIdx(0)`. const FIRST_VARIANT = 0; diff --git a/compiler/rustc_trait_selection/Cargo.toml b/compiler/rustc_trait_selection/Cargo.toml index 667ee3d4e1c6..7d098180b931 100644 --- a/compiler/rustc_trait_selection/Cargo.toml +++ b/compiler/rustc_trait_selection/Cargo.toml @@ -17,7 +17,6 @@ rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } rustc_parse_format = { path = "../rustc_parse_format" } rustc_query_system = { path = "../rustc_query_system" } -rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index a5f90421de5f..765cbceb7d1c 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -95,6 +95,7 @@ impl DebugWithInfcx for ConstKind { rustc_index::newtype_index! { /// A **`const`** **v**ariable **ID**. + #[encodable] #[debug_format = "?{}c"] #[gate_rustc_only] pub struct ConstVid {} @@ -108,6 +109,7 @@ rustc_index::newtype_index! { /// relate an effect variable with a normal one, we would ICE, which can catch bugs /// where we are not correctly using the effect var for an effect param. Fallback /// is also implemented on top of having separate effect and normal const variables. + #[encodable] #[debug_format = "?{}e"] #[gate_rustc_only] pub struct EffectVid {} diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index d293a9341fe2..ba7774863ef4 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -92,6 +92,7 @@ rustc_index::newtype_index! { /// /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] + #[encodable] #[debug_format = "DebruijnIndex({})"] #[gate_rustc_only] pub struct DebruijnIndex { @@ -293,6 +294,7 @@ rustc_index::newtype_index! { /// type -- an idealized representative of "types in general" that we /// use for checking generic functions. #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] + #[encodable] #[debug_format = "U{}"] #[gate_rustc_only] pub struct UniverseIndex {} @@ -335,6 +337,7 @@ impl UniverseIndex { rustc_index::newtype_index! { #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] + #[encodable] #[debug_format = "{}"] #[gate_rustc_only] pub struct BoundVar {} diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 494eeaf3dc88..a3e94d5c1378 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -622,6 +622,7 @@ pub struct FloatVarValue(pub FloatTy); rustc_index::newtype_index! { /// A **ty**pe **v**ariable **ID**. + #[encodable] #[debug_format = "?{}t"] #[gate_rustc_only] pub struct TyVid {} @@ -629,6 +630,7 @@ rustc_index::newtype_index! { rustc_index::newtype_index! { /// An **int**egral (`u32`, `i32`, `usize`, etc.) type **v**ariable **ID**. + #[encodable] #[debug_format = "?{}i"] #[gate_rustc_only] pub struct IntVid {} @@ -636,6 +638,7 @@ rustc_index::newtype_index! { rustc_index::newtype_index! { /// A **float**ing-point (`f32` or `f64`) type **v**ariable **ID**. + #[encodable] #[debug_format = "?{}f"] #[gate_rustc_only] pub struct FloatVid {} From 7060fc8327f457882823fcc1737a964407eed0d6 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 21 Nov 2023 17:35:46 +1100 Subject: [PATCH 46/66] Replace `no_ord_impl` with `orderable`. Similar to the previous commit, this replaces `newtype_index`'s opt-out `no_ord_impl` attribute with the opt-in `orderable` attribute. --- compiler/rustc_ast/src/ast.rs | 1 + compiler/rustc_ast/src/node_id.rs | 1 + compiler/rustc_borrowck/src/constraints/mod.rs | 1 + compiler/rustc_borrowck/src/dataflow.rs | 1 + compiler/rustc_borrowck/src/location.rs | 1 + compiler/rustc_borrowck/src/region_infer/values.rs | 1 + compiler/rustc_data_structures/src/graph/dominators/mod.rs | 1 + compiler/rustc_hir/src/hir_id.rs | 1 + .../src/coherence/inherent_impls_overlap.rs | 1 + compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs | 2 ++ compiler/rustc_index/src/vec/tests.rs | 1 + compiler/rustc_index_macros/src/newtype.rs | 6 +++--- .../rustc_infer/src/infer/region_constraints/leak_check.rs | 2 ++ compiler/rustc_middle/src/middle/region.rs | 1 + compiler/rustc_middle/src/mir/coverage.rs | 2 ++ compiler/rustc_middle/src/mir/mod.rs | 3 +++ compiler/rustc_middle/src/ty/sty.rs | 1 + compiler/rustc_mir_build/src/build/scope.rs | 1 + compiler/rustc_mir_dataflow/src/move_paths/mod.rs | 2 ++ compiler/rustc_mir_transform/src/coverage/graph.rs | 1 + compiler/rustc_span/src/def_id.rs | 2 ++ compiler/rustc_span/src/hygiene.rs | 2 +- compiler/rustc_span/src/symbol.rs | 1 + compiler/rustc_target/src/abi/mod.rs | 2 ++ compiler/rustc_trait_selection/src/solve/search_graph.rs | 1 + compiler/rustc_type_ir/src/const_kind.rs | 2 ++ compiler/rustc_type_ir/src/lib.rs | 3 +++ compiler/rustc_type_ir/src/ty_kind.rs | 3 +++ 28 files changed, 43 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index e311352c93de..83fe95f16f9a 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2574,6 +2574,7 @@ pub enum AttrStyle { } rustc_index::newtype_index! { + #[orderable] #[debug_format = "AttrId({})"] pub struct AttrId {} } diff --git a/compiler/rustc_ast/src/node_id.rs b/compiler/rustc_ast/src/node_id.rs index 48081582fc32..1cd244953090 100644 --- a/compiler/rustc_ast/src/node_id.rs +++ b/compiler/rustc_ast/src/node_id.rs @@ -9,6 +9,7 @@ rustc_index::newtype_index! { /// /// [`DefId`]: rustc_span::def_id::DefId #[encodable] + #[orderable] #[debug_format = "NodeId({})"] pub struct NodeId { /// The [`NodeId`] used to represent the root of the crate. diff --git a/compiler/rustc_borrowck/src/constraints/mod.rs b/compiler/rustc_borrowck/src/constraints/mod.rs index 315886bbe29b..041ac75ec016 100644 --- a/compiler/rustc_borrowck/src/constraints/mod.rs +++ b/compiler/rustc_borrowck/src/constraints/mod.rs @@ -122,6 +122,7 @@ rustc_index::newtype_index! { } rustc_index::newtype_index! { + #[orderable] #[debug_format = "ConstraintSccIndex({})"] pub struct ConstraintSccIndex {} } diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs index 8676d2ba7c4c..27b558be3b77 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -109,6 +109,7 @@ impl_visitable! { } rustc_index::newtype_index! { + #[orderable] #[debug_format = "bw{}"] pub struct BorrowIndex {} } diff --git a/compiler/rustc_borrowck/src/location.rs b/compiler/rustc_borrowck/src/location.rs index 0e669abfd14a..6f09393169f3 100644 --- a/compiler/rustc_borrowck/src/location.rs +++ b/compiler/rustc_borrowck/src/location.rs @@ -20,6 +20,7 @@ pub struct LocationTable { } rustc_index::newtype_index! { + #[orderable] #[debug_format = "LocationIndex({})"] pub struct LocationIndex {} } diff --git a/compiler/rustc_borrowck/src/region_infer/values.rs b/compiler/rustc_borrowck/src/region_infer/values.rs index 38452df32e9e..96b3a4e6d18f 100644 --- a/compiler/rustc_borrowck/src/region_infer/values.rs +++ b/compiler/rustc_borrowck/src/region_infer/values.rs @@ -90,6 +90,7 @@ impl RegionValueElements { rustc_index::newtype_index! { /// A single integer representing a `Location` in the MIR control-flow /// graph. Constructed efficiently from `RegionValueElements`. + #[orderable] #[debug_format = "PointIndex({})"] pub struct PointIndex {} } diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index 5dd414cfd41f..4b819e1cbd61 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -23,6 +23,7 @@ struct PreOrderFrame { } rustc_index::newtype_index! { + #[orderable] struct PreorderIndex {} } diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index c40a317947c0..d339075c171d 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -155,6 +155,7 @@ rustc_index::newtype_index! { /// tree or hash map. #[derive(HashStable_Generic)] #[encodable] + #[orderable] pub struct ItemLocalId {} } diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs index cbce8c4b8b83..3f8c0db8752d 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -198,6 +198,7 @@ impl<'tcx> InherentOverlapChecker<'tcx> { // entire graph when there are many connected regions. rustc_index::newtype_index! { + #[orderable] pub struct RegionId {} } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs index 7aadb95d9393..566d407d23c1 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs @@ -4,11 +4,13 @@ use rustc_middle::ty::error::TypeError; use std::cmp; rustc_index::newtype_index! { + #[orderable] #[debug_format = "ExpectedIdx({})"] pub(crate) struct ExpectedIdx {} } rustc_index::newtype_index! { + #[orderable] #[debug_format = "ProvidedIdx({})"] pub(crate) struct ProvidedIdx {} } diff --git a/compiler/rustc_index/src/vec/tests.rs b/compiler/rustc_index/src/vec/tests.rs index 1959f4e07b7c..381d79c24fcb 100644 --- a/compiler/rustc_index/src/vec/tests.rs +++ b/compiler/rustc_index/src/vec/tests.rs @@ -2,6 +2,7 @@ use crate as rustc_index; crate::newtype_index! { + #[orderable] #[max = 0xFFFF_FFFA] struct MyIdx {} } diff --git a/compiler/rustc_index_macros/src/newtype.rs b/compiler/rustc_index_macros/src/newtype.rs index 62de5c7c6c16..df1318c835e2 100644 --- a/compiler/rustc_index_macros/src/newtype.rs +++ b/compiler/rustc_index_macros/src/newtype.rs @@ -23,7 +23,7 @@ impl Parse for Newtype { let mut max = None; let mut consts = Vec::new(); let mut encodable = false; - let mut ord = true; + let mut ord = false; let mut gate_rustc_only = quote! {}; let mut gate_rustc_only_cfg = quote! { all() }; @@ -38,8 +38,8 @@ impl Parse for Newtype { encodable = true; false } - "no_ord_impl" => { - ord = false; + "orderable" => { + ord = true; false } "max" => { diff --git a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs index 479343c3ec28..e06596df7b94 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs @@ -341,11 +341,13 @@ impl<'tcx> SccUniverse<'tcx> { } rustc_index::newtype_index! { + #[orderable] #[debug_format = "LeakCheckNode({})"] struct LeakCheckNode {} } rustc_index::newtype_index! { + #[orderable] #[debug_format = "LeakCheckScc({})"] struct LeakCheckScc {} } diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index a0765770a8f6..b8f04ed03dca 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -149,6 +149,7 @@ rustc_index::newtype_index! { /// and thus does not include EXPR_2, but covers the `...`. #[derive(HashStable)] #[encodable] + #[orderable] pub struct FirstStatementIndex {} } diff --git a/compiler/rustc_middle/src/mir/coverage.rs b/compiler/rustc_middle/src/mir/coverage.rs index ccd2cd76ad87..f15ee0082ced 100644 --- a/compiler/rustc_middle/src/mir/coverage.rs +++ b/compiler/rustc_middle/src/mir/coverage.rs @@ -18,6 +18,7 @@ rustc_index::newtype_index! { /// to use a larger representation on the Rust side. #[derive(HashStable)] #[encodable] + #[orderable] #[max = 0xFFFF_FFFF] #[debug_format = "CounterId({})"] pub struct CounterId {} @@ -39,6 +40,7 @@ rustc_index::newtype_index! { /// to use a larger representation on the Rust side. #[derive(HashStable)] #[encodable] + #[orderable] #[max = 0xFFFF_FFFF] #[debug_format = "ExpressionId({})"] pub struct ExpressionId {} diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 4e6f5c3fb4e0..1e5a7401c6f9 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -737,6 +737,7 @@ impl SourceInfo { rustc_index::newtype_index! { #[derive(HashStable)] #[encodable] + #[orderable] #[debug_format = "_{}"] pub struct Local { const RETURN_PLACE = 0; @@ -1173,6 +1174,7 @@ rustc_index::newtype_index! { /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/ #[derive(HashStable)] #[encodable] + #[orderable] #[debug_format = "bb{}"] pub struct BasicBlock { const START_BLOCK = 0; @@ -1537,6 +1539,7 @@ impl UserTypeProjection { rustc_index::newtype_index! { #[derive(HashStable)] #[encodable] + #[orderable] #[debug_format = "promoted[{}]"] pub struct Promoted {} } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index f3915f6b4103..f12a512da313 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1613,6 +1613,7 @@ rustc_index::newtype_index! { /// A **region** (lifetime) **v**ariable **ID**. #[derive(HashStable)] #[encodable] + #[orderable] #[debug_format = "'?{}"] pub struct RegionVid {} } diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index d6ca873e9922..993fee95895c 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -186,6 +186,7 @@ pub(crate) enum BreakableTarget { } rustc_index::newtype_index! { + #[orderable] struct DropIdx {} } diff --git a/compiler/rustc_mir_dataflow/src/move_paths/mod.rs b/compiler/rustc_mir_dataflow/src/move_paths/mod.rs index 7ab1a9ed069f..22cf3999239c 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/mod.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/mod.rs @@ -14,6 +14,7 @@ use self::abs_domain::{AbstractElem, Lift}; mod abs_domain; rustc_index::newtype_index! { + #[orderable] #[debug_format = "mp{}"] pub struct MovePathIndex {} } @@ -25,6 +26,7 @@ impl polonius_engine::Atom for MovePathIndex { } rustc_index::newtype_index! { + #[orderable] #[debug_format = "mo{}"] pub struct MoveOutIndex {} } diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 7defc9ec148a..0d807db404c8 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -264,6 +264,7 @@ impl graph::WithPredecessors for CoverageGraph { rustc_index::newtype_index! { /// A node in the control-flow graph of CoverageGraph. + #[orderable] #[debug_format = "bcb{}"] pub(super) struct BasicCoverageBlock { const START_BCB = 0; diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index 595456e6d6a1..4b5bd75d5b10 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -13,6 +13,7 @@ pub type StableCrateIdMap = indexmap::IndexMap>; rustc_index::newtype_index! { + #[orderable] #[debug_format = "crate{}"] pub struct CrateNum {} } @@ -212,6 +213,7 @@ rustc_index::newtype_index! { /// A DefIndex is an index into the hir-map for a crate, identifying a /// particular definition. It should really be considered an interned /// shorthand for a particular DefPath. + #[orderable] #[debug_format = "DefIndex({})"] pub struct DefIndex { /// The crate root is always assigned index 0 by the AST Map code, diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 8c6600c4e531..b717229b68df 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -60,6 +60,7 @@ pub struct SyntaxContextData { rustc_index::newtype_index! { /// A unique ID associated with a macro invocation and expansion. + #[orderable] pub struct ExpnIndex {} } @@ -79,7 +80,6 @@ impl fmt::Debug for ExpnId { rustc_index::newtype_index! { /// A unique ID associated with a macro invocation and expansion. - #[no_ord_impl] #[debug_format = "expn{}"] pub struct LocalExpnId {} } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 2e3b54464050..ea80bc82bd1f 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2018,6 +2018,7 @@ impl fmt::Display for MacroRulesNormalizedIdent { pub struct Symbol(SymbolIndex); rustc_index::newtype_index! { + #[orderable] struct SymbolIndex {} } diff --git a/compiler/rustc_target/src/abi/mod.rs b/compiler/rustc_target/src/abi/mod.rs index c1fbc2980a97..a274790bffcf 100644 --- a/compiler/rustc_target/src/abi/mod.rs +++ b/compiler/rustc_target/src/abi/mod.rs @@ -43,6 +43,7 @@ rustc_index::newtype_index! { /// `f` is `FieldIdx(1)` in `VariantIdx(0)`. #[derive(HashStable_Generic)] #[encodable] + #[orderable] pub struct FieldIdx {} } @@ -59,6 +60,7 @@ rustc_index::newtype_index! { /// with variant index zero, aka [`FIRST_VARIANT`]. #[derive(HashStable_Generic)] #[encodable] + #[orderable] pub struct VariantIdx { /// Equivalent to `VariantIdx(0)`. const FIRST_VARIANT = 0; diff --git a/compiler/rustc_trait_selection/src/solve/search_graph.rs b/compiler/rustc_trait_selection/src/solve/search_graph.rs index 68f81a055361..71adebffc151 100644 --- a/compiler/rustc_trait_selection/src/solve/search_graph.rs +++ b/compiler/rustc_trait_selection/src/solve/search_graph.rs @@ -13,6 +13,7 @@ use rustc_session::Limit; use std::collections::hash_map::Entry; rustc_index::newtype_index! { + #[orderable] pub struct StackDepth {} } diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index 765cbceb7d1c..409033a2d8d0 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -96,6 +96,7 @@ impl DebugWithInfcx for ConstKind { rustc_index::newtype_index! { /// A **`const`** **v**ariable **ID**. #[encodable] + #[orderable] #[debug_format = "?{}c"] #[gate_rustc_only] pub struct ConstVid {} @@ -110,6 +111,7 @@ rustc_index::newtype_index! { /// where we are not correctly using the effect var for an effect param. Fallback /// is also implemented on top of having separate effect and normal const variables. #[encodable] + #[orderable] #[debug_format = "?{}e"] #[gate_rustc_only] pub struct EffectVid {} diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index ba7774863ef4..2aeb4230bb83 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -93,6 +93,7 @@ rustc_index::newtype_index! { /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] #[encodable] + #[orderable] #[debug_format = "DebruijnIndex({})"] #[gate_rustc_only] pub struct DebruijnIndex { @@ -295,6 +296,7 @@ rustc_index::newtype_index! { /// use for checking generic functions. #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] #[encodable] + #[orderable] #[debug_format = "U{}"] #[gate_rustc_only] pub struct UniverseIndex {} @@ -338,6 +340,7 @@ impl UniverseIndex { rustc_index::newtype_index! { #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] #[encodable] + #[orderable] #[debug_format = "{}"] #[gate_rustc_only] pub struct BoundVar {} diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index a3e94d5c1378..3d4e7f77a4f2 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -623,6 +623,7 @@ pub struct FloatVarValue(pub FloatTy); rustc_index::newtype_index! { /// A **ty**pe **v**ariable **ID**. #[encodable] + #[orderable] #[debug_format = "?{}t"] #[gate_rustc_only] pub struct TyVid {} @@ -631,6 +632,7 @@ rustc_index::newtype_index! { rustc_index::newtype_index! { /// An **int**egral (`u32`, `i32`, `usize`, etc.) type **v**ariable **ID**. #[encodable] + #[orderable] #[debug_format = "?{}i"] #[gate_rustc_only] pub struct IntVid {} @@ -639,6 +641,7 @@ rustc_index::newtype_index! { rustc_index::newtype_index! { /// A **float**ing-point (`f32` or `f64`) type **v**ariable **ID**. #[encodable] + #[orderable] #[debug_format = "?{}f"] #[gate_rustc_only] pub struct FloatVid {} From 0991374bd1c99e1e64f47a884b10932b39ad61c2 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 21 Nov 2023 18:42:34 +1100 Subject: [PATCH 47/66] Document `newtype_index` attributes. --- compiler/rustc_index_macros/src/lib.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_index_macros/src/lib.rs b/compiler/rustc_index_macros/src/lib.rs index f6a6175374ac..13500949a221 100644 --- a/compiler/rustc_index_macros/src/lib.rs +++ b/compiler/rustc_index_macros/src/lib.rs @@ -18,8 +18,19 @@ mod newtype; /// to create/return a value. /// /// Internally, the index uses a u32, so the index must not exceed -/// `u32::MAX`. You can also customize things like the `Debug` impl, -/// what traits are derived, and so forth via the macro. +/// `u32::MAX`. +/// +/// The impls provided by default are Clone, Copy, PartialEq, Eq, and Hash. +/// +/// Accepted attributes for customization: +/// - #[derive(HashStable_Generic)]/#[derive(HashStable)]: derives +/// `HashStable`, as normal. +/// - #[encodable]: derives `Encodable`/`Decodable`. +/// - #[orderable]: derives `PartialOrd`/`Ord`, plus step-related methods. +/// - #[debug_format = "Foo({})"]: derives `Debug` with particular output. +/// - #[max = 0xFFFF_FFFD]: specifies the max value, which allows niche +/// optimizations. The default max value is 0xFFFF_FF00. +/// - #[gate_rustc_only]: makes parts of the generated code nightly-only. #[proc_macro] #[cfg_attr( feature = "nightly", From 4c2d6de70e66f6e2c882acbc9be1c5a53d8a65e4 Mon Sep 17 00:00:00 2001 From: Urgau Date: Tue, 21 Nov 2023 13:58:01 +0100 Subject: [PATCH 48/66] Stabilize RFC3324 dyn upcasting coercion Aka trait_upcasting feature. And also adjust the `deref_into_dyn_supertrait` lint. --- compiler/rustc_feature/src/accepted.rs | 3 ++ compiler/rustc_feature/src/unstable.rs | 3 -- compiler/rustc_hir_typeck/src/coercion.rs | 23 --------- compiler/rustc_lint/messages.ftl | 5 +- .../src/deref_into_dyn_supertrait.rs | 15 ++---- compiler/rustc_lint/src/lints.rs | 6 +-- compiler/rustc_middle/src/lib.rs | 2 +- .../src/traits/select/candidate_assembly.rs | 51 ------------------- library/core/tests/lib.rs | 2 +- .../src/language-features/trait-upcasting.md | 27 ---------- src/tools/miri/src/lib.rs | 2 +- .../tests/fail/dyn-upcast-trait-mismatch.rs | 3 -- src/tools/miri/tests/pass/box-custom-alloc.rs | 3 +- src/tools/miri/tests/pass/dyn-upcast.rs | 3 -- tests/ui/codegen/issue-99551.rs | 1 - .../ui/dyn-star/no-unsize-coerce-dyn-trait.rs | 2 +- .../no-unsize-coerce-dyn-trait.stderr | 2 +- tests/ui/dyn-star/upcast.rs | 2 +- tests/ui/dyn-star/upcast.stderr | 2 +- .../feature-gate-trait_upcasting.rs | 13 ----- .../feature-gate-trait_upcasting.stderr | 13 ----- .../traits/new-solver/normalize-unsize-rhs.rs | 2 - .../trait-upcast-lhs-needs-normalization.rs | 2 - .../traits/new-solver/upcast-right-substs.rs | 2 - .../traits/new-solver/upcast-wrong-substs.rs | 2 - .../new-solver/upcast-wrong-substs.stderr | 2 +- .../alias-where-clause-isnt-supertrait.rs | 1 - .../alias-where-clause-isnt-supertrait.stderr | 2 +- tests/ui/traits/trait-upcasting/basic.rs | 2 - .../correct-supertrait-substitution.rs | 1 - ...-deny-regions.rs => deref-lint-regions.rs} | 5 +- .../trait-upcasting/deref-lint-regions.stderr | 14 +++++ .../{migrate-lint-deny.rs => deref-lint.rs} | 6 +-- .../traits/trait-upcasting/deref-lint.stderr | 14 +++++ tests/ui/traits/trait-upcasting/diamond.rs | 2 - .../trait-upcasting/fewer-associated.rs | 2 - .../illegal-upcast-from-impl.current.stderr | 2 +- .../illegal-upcast-from-impl.next.stderr | 2 +- .../illegal-upcast-from-impl.rs | 2 - .../inference-behavior-change-deref.rs | 1 - .../inference-behavior-change-deref.stderr | 2 +- .../traits/trait-upcasting/invalid-upcast.rs | 2 - .../trait-upcasting/invalid-upcast.stderr | 30 +++++------ .../issue-11515-upcast-fn_mut-fn.rs | 1 - .../issue-11515.current.stderr | 13 ----- .../trait-upcasting/issue-11515.next.stderr | 13 ----- .../ui/traits/trait-upcasting/issue-11515.rs | 3 +- tests/ui/traits/trait-upcasting/lifetime.rs | 2 - .../migrate-lint-deny-regions.stderr | 19 ------- .../trait-upcasting/migrate-lint-deny.stderr | 19 ------- .../multiple-occurrence-ambiguousity.rs | 1 - .../multiple-occurrence-ambiguousity.stderr | 2 +- .../traits/trait-upcasting/normalization.rs | 2 - .../ui/traits/trait-upcasting/replace-vptr.rs | 2 - tests/ui/traits/trait-upcasting/struct.rs | 2 - .../traits/trait-upcasting/subtrait-method.rs | 2 - .../trait-upcasting/subtrait-method.stderr | 40 +++++++-------- .../type-checking-test-1.current.stderr | 2 +- .../type-checking-test-1.next.stderr | 2 +- .../trait-upcasting/type-checking-test-1.rs | 2 - .../trait-upcasting/type-checking-test-2.rs | 2 - .../type-checking-test-2.stderr | 4 +- .../trait-upcasting/type-checking-test-3.rs | 2 - .../type-checking-test-3.stderr | 4 +- .../trait-upcasting/type-checking-test-4.rs | 2 - .../type-checking-test-4.stderr | 12 ++--- .../upcast-through-struct-tail.current.stderr | 13 ----- .../upcast-through-struct-tail.next.stderr | 13 ----- .../upcast-through-struct-tail.rs | 2 +- 69 files changed, 107 insertions(+), 357 deletions(-) delete mode 100644 src/doc/unstable-book/src/language-features/trait-upcasting.md delete mode 100644 tests/ui/feature-gates/feature-gate-trait_upcasting.rs delete mode 100644 tests/ui/feature-gates/feature-gate-trait_upcasting.stderr rename tests/ui/traits/trait-upcasting/{migrate-lint-deny-regions.rs => deref-lint-regions.rs} (53%) create mode 100644 tests/ui/traits/trait-upcasting/deref-lint-regions.stderr rename tests/ui/traits/trait-upcasting/{migrate-lint-deny.rs => deref-lint.rs} (60%) create mode 100644 tests/ui/traits/trait-upcasting/deref-lint.stderr delete mode 100644 tests/ui/traits/trait-upcasting/issue-11515.current.stderr delete mode 100644 tests/ui/traits/trait-upcasting/issue-11515.next.stderr delete mode 100644 tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr delete mode 100644 tests/ui/traits/trait-upcasting/migrate-lint-deny.stderr delete mode 100644 tests/ui/traits/trait-upcasting/upcast-through-struct-tail.current.stderr delete mode 100644 tests/ui/traits/trait-upcasting/upcast-through-struct-tail.next.stderr diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 577657ff7947..37ef4d869899 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -338,6 +338,9 @@ declare_features! ( /// Allows `#[track_caller]` to be used which provides /// accurate caller location reporting during panic (RFC 2091). (accepted, track_caller, "1.46.0", Some(47809), None), + /// Allows dyn upcasting trait objects via supertraits. + /// Dyn upcasting is casting, e.g., `dyn Foo -> dyn Bar` where `Foo: Bar`. + (accepted, trait_upcasting, "CURRENT_RUSTC_VERSION", Some(65991), None), /// Allows #[repr(transparent)] on univariant enums (RFC 2645). (accepted, transparent_enums, "1.42.0", Some(60405), None), /// Allows indexing tuples. diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index b11b190bdeda..d1b3fec8a0bb 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -562,9 +562,6 @@ declare_features! ( (unstable, thread_local, "1.0.0", Some(29594), None), /// Allows defining `trait X = A + B;` alias items. (unstable, trait_alias, "1.24.0", Some(41517), None), - /// Allows dyn upcasting trait objects via supertraits. - /// Dyn upcasting is casting, e.g., `dyn Foo -> dyn Bar` where `Foo: Bar`. - (unstable, trait_upcasting, "1.56.0", Some(65991), None), /// Allows for transmuting between arrays with sizes that contain generic consts. (unstable, transmute_generic_consts, "1.70.0", Some(109929), None), /// Allows #[repr(transparent)] on unions (RFC 2645). diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 971f10631df4..ae2a4a9504ce 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -626,7 +626,6 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { )]; let mut has_unsized_tuple_coercion = false; - let mut has_trait_upcasting_coercion = None; // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where @@ -694,13 +693,6 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // these here and emit a feature error if coercion doesn't fail // due to another reason. match impl_source { - traits::ImplSource::Builtin( - BuiltinImplSource::TraitUpcasting { .. }, - _, - ) => { - has_trait_upcasting_coercion = - Some((trait_pred.self_ty(), trait_pred.trait_ref.args.type_at(1))); - } traits::ImplSource::Builtin(BuiltinImplSource::TupleUnsizing, _) => { has_unsized_tuple_coercion = true; } @@ -711,21 +703,6 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { } } - if let Some((sub, sup)) = has_trait_upcasting_coercion - && !self.tcx().features().trait_upcasting - { - // Renders better when we erase regions, since they're not really the point here. - let (sub, sup) = self.tcx.erase_regions((sub, sup)); - let mut err = feature_err( - &self.tcx.sess.parse_sess, - sym::trait_upcasting, - self.cause.span, - format!("cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental"), - ); - err.note(format!("required when coercing `{source}` into `{target}`")); - err.emit(); - } - if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion { feature_err( &self.tcx.sess.parse_sess, diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index cb2e373c6f90..85bae6f70f79 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -490,8 +490,9 @@ lint_requested_level = requested on the command line with `{$level} {$lint_name} lint_span_use_eq_ctxt = use `.eq_ctxt()` instead of `.ctxt() == .ctxt()` -lint_supertrait_as_deref_target = `{$t}` implements `Deref` with supertrait `{$target_principal}` as target - .label = target type is set here +lint_supertrait_as_deref_target = this `Deref` implementation is covered by an implicit supertrait coercion + .help = consider removing this implementation or replacing it with a method instead + .label = target type is a supertrait of `{$t}` lint_suspicious_double_ref_clone = using `.clone()` on a double reference, which returns `{$ty}` instead of cloning the inner type diff --git a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs index d3e2d5c76465..93c7c37c6550 100644 --- a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs +++ b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs @@ -5,7 +5,6 @@ use crate::{ use rustc_hir as hir; use rustc_middle::ty; -use rustc_session::lint::FutureIncompatibilityReason; use rustc_span::sym; use rustc_trait_selection::traits::supertraits; @@ -13,9 +12,6 @@ declare_lint! { /// The `deref_into_dyn_supertrait` lint is output whenever there is a use of the /// `Deref` implementation with a `dyn SuperTrait` type as `Output`. /// - /// These implementations will become shadowed when the `trait_upcasting` feature is stabilized. - /// The `deref` functions will no longer be called implicitly, so there might be behavior change. - /// /// ### Example /// /// ```rust,compile_fail @@ -44,15 +40,10 @@ declare_lint! { /// /// ### Explanation /// - /// The dyn upcasting coercion feature adds new coercion rules, taking priority - /// over certain other coercion rules, which will cause some behavior change. + /// The implicit dyn upcasting coercion take priority over those `Deref` impls. pub DEREF_INTO_DYN_SUPERTRAIT, Warn, - "`Deref` implementation usage with a supertrait trait object for output might be shadowed in the future", - @future_incompatible = FutureIncompatibleInfo { - reason: FutureIncompatibilityReason::FutureReleaseSemanticsChange, - reference: "issue #89460 ", - }; + "`Deref` implementation usage with a supertrait trait object for output are shadow by implicit coercion", } declare_lint_pass!(DerefIntoDynSupertrait => [DEREF_INTO_DYN_SUPERTRAIT]); @@ -90,7 +81,7 @@ impl<'tcx> LateLintPass<'tcx> for DerefIntoDynSupertrait { cx.emit_spanned_lint( DEREF_INTO_DYN_SUPERTRAIT, tcx.def_span(item.owner_id.def_id), - SupertraitAsDerefTarget { t, target_principal, label }, + SupertraitAsDerefTarget { t, label }, ); } } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index c4d54c95e226..69d3238ce01a 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -10,9 +10,7 @@ use rustc_errors::{ }; use rustc_hir::def_id::DefId; use rustc_macros::{LintDiagnostic, Subdiagnostic}; -use rustc_middle::ty::{ - inhabitedness::InhabitedPredicate, Clause, PolyExistentialTraitRef, Ty, TyCtxt, -}; +use rustc_middle::ty::{inhabitedness::InhabitedPredicate, Clause, Ty, TyCtxt}; use rustc_session::parse::ParseSess; use rustc_span::{edition::Edition, sym, symbol::Ident, Span, Symbol}; @@ -556,9 +554,9 @@ pub enum BuiltinSpecialModuleNameUsed { // deref_into_dyn_supertrait.rs #[derive(LintDiagnostic)] #[diag(lint_supertrait_as_deref_target)] +#[help] pub struct SupertraitAsDerefTarget<'a> { pub t: Ty<'a>, - pub target_principal: PolyExistentialTraitRef<'a>, #[subdiagnostic] pub label: Option, } diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index 4af875e8d79d..e5244c1862e4 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -49,7 +49,7 @@ #![feature(associated_type_bounds)] #![feature(rustc_attrs)] #![feature(control_flow_enum)] -#![feature(trait_upcasting)] +#![cfg_attr(bootstrap, feature(trait_upcasting))] #![feature(trusted_step)] #![feature(try_blocks)] #![feature(try_reserve_kind)] diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 307a36761f28..310711f91a7c 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -9,13 +9,10 @@ use hir::def_id::DefId; use hir::LangItem; use rustc_hir as hir; -use rustc_infer::traits::ObligationCause; use rustc_infer::traits::{Obligation, PolyTraitObligation, SelectionError}; use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams}; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; -use crate::traits; -use crate::traits::query::evaluate_obligation::InferCtxtExt; use crate::traits::util; use super::BuiltinImplConditions; @@ -690,45 +687,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }) } - /// Temporary migration for #89190 - fn need_migrate_deref_output_trait_object( - &mut self, - ty: Ty<'tcx>, - param_env: ty::ParamEnv<'tcx>, - cause: &ObligationCause<'tcx>, - ) -> Option> { - let tcx = self.tcx(); - if tcx.features().trait_upcasting { - return None; - } - - // - let trait_ref = ty::TraitRef::new(tcx, tcx.lang_items().deref_trait()?, [ty]); - - let obligation = - traits::Obligation::new(tcx, cause.clone(), param_env, ty::Binder::dummy(trait_ref)); - if !self.infcx.predicate_may_hold(&obligation) { - return None; - } - - self.infcx.probe(|_| { - let ty = traits::normalize_projection_type( - self, - param_env, - ty::AliasTy::new(tcx, tcx.lang_items().deref_target()?, trait_ref.args), - cause.clone(), - 0, - // We're *intentionally* throwing these away, - // since we don't actually use them. - &mut vec![], - ) - .ty() - .unwrap(); - - if let ty::Dynamic(data, ..) = ty.kind() { data.principal() } else { None } - }) - } - /// Searches for unsizing that might apply to `obligation`. fn assemble_candidates_for_unsizing( &mut self, @@ -786,15 +744,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let principal_a = a_data.principal().unwrap(); let target_trait_did = principal_def_id_b.unwrap(); let source_trait_ref = principal_a.with_self_ty(self.tcx(), source); - if let Some(deref_trait_ref) = self.need_migrate_deref_output_trait_object( - source, - obligation.param_env, - &obligation.cause, - ) { - if deref_trait_ref.def_id() == target_trait_did { - return; - } - } for (idx, upcast_trait_ref) in util::supertraits(self.tcx(), source_trait_ref).enumerate() diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 3a459052d265..3fbb058b09ba 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -111,7 +111,7 @@ #![feature(slice_flatten)] #![feature(error_generic_member_access)] #![feature(error_in_core)] -#![feature(trait_upcasting)] +#![cfg_attr(bootstrap, feature(trait_upcasting))] #![feature(utf8_chunks)] #![feature(is_ascii_octdigit)] #![feature(get_many_mut)] diff --git a/src/doc/unstable-book/src/language-features/trait-upcasting.md b/src/doc/unstable-book/src/language-features/trait-upcasting.md deleted file mode 100644 index 3697ae38f9d8..000000000000 --- a/src/doc/unstable-book/src/language-features/trait-upcasting.md +++ /dev/null @@ -1,27 +0,0 @@ -# `trait_upcasting` - -The tracking issue for this feature is: [#65991] - -[#65991]: https://github.com/rust-lang/rust/issues/65991 - ------------------------- - -The `trait_upcasting` feature adds support for trait upcasting coercion. This allows a -trait object of type `dyn Bar` to be cast to a trait object of type `dyn Foo` -so long as `Bar: Foo`. - -```rust,edition2018 -#![feature(trait_upcasting)] -#![allow(incomplete_features)] - -trait Foo {} - -trait Bar: Foo {} - -impl Foo for i32 {} - -impl Bar for T {} - -let bar: &dyn Bar = &123; -let foo: &dyn Foo = bar; -``` diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index 119ec555b2e0..d906553ec402 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -11,7 +11,7 @@ #![feature(round_ties_even)] #![feature(let_chains)] #![feature(lint_reasons)] -#![feature(trait_upcasting)] +#![cfg_attr(bootstrap, feature(trait_upcasting))] // Configure clippy and other lints #![allow( clippy::collapsible_else_if, diff --git a/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs b/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs index 648ac07c43ec..7d46ecd8f6ea 100644 --- a/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs +++ b/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs @@ -1,6 +1,3 @@ -#![feature(trait_upcasting)] -#![allow(incomplete_features)] - trait Foo: PartialEq + std::fmt::Debug + Send + Sync { fn a(&self) -> i32 { 10 diff --git a/src/tools/miri/tests/pass/box-custom-alloc.rs b/src/tools/miri/tests/pass/box-custom-alloc.rs index 155e3d74ab9c..3d055961d15d 100644 --- a/src/tools/miri/tests/pass/box-custom-alloc.rs +++ b/src/tools/miri/tests/pass/box-custom-alloc.rs @@ -1,7 +1,6 @@ //@revisions: stack tree //@[tree]compile-flags: -Zmiri-tree-borrows -#![allow(incomplete_features)] // for trait upcasting -#![feature(allocator_api, trait_upcasting)] +#![feature(allocator_api)] use std::alloc::Layout; use std::alloc::{AllocError, Allocator}; diff --git a/src/tools/miri/tests/pass/dyn-upcast.rs b/src/tools/miri/tests/pass/dyn-upcast.rs index 8432012a9ba5..ddaefeca3a3b 100644 --- a/src/tools/miri/tests/pass/dyn-upcast.rs +++ b/src/tools/miri/tests/pass/dyn-upcast.rs @@ -1,6 +1,3 @@ -#![feature(trait_upcasting)] -#![allow(incomplete_features)] - fn main() { basic(); diamond(); diff --git a/tests/ui/codegen/issue-99551.rs b/tests/ui/codegen/issue-99551.rs index b223aff4e949..9e203fba113c 100644 --- a/tests/ui/codegen/issue-99551.rs +++ b/tests/ui/codegen/issue-99551.rs @@ -1,5 +1,4 @@ // build-pass -#![feature(trait_upcasting)] pub trait A {} pub trait B {} diff --git a/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.rs b/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.rs index a4eb669e3210..0201c8897065 100644 --- a/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.rs +++ b/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.rs @@ -1,4 +1,4 @@ -#![feature(dyn_star, trait_upcasting)] +#![feature(dyn_star)] //~^ WARN the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes trait A: B {} diff --git a/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.stderr b/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.stderr index c7f1a4b9ae11..50aa79f5c0f9 100644 --- a/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.stderr +++ b/tests/ui/dyn-star/no-unsize-coerce-dyn-trait.stderr @@ -1,7 +1,7 @@ warning: the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/no-unsize-coerce-dyn-trait.rs:1:12 | -LL | #![feature(dyn_star, trait_upcasting)] +LL | #![feature(dyn_star)] | ^^^^^^^^ | = note: see issue #102425 for more information diff --git a/tests/ui/dyn-star/upcast.rs b/tests/ui/dyn-star/upcast.rs index c667ac143a39..7748cdda943c 100644 --- a/tests/ui/dyn-star/upcast.rs +++ b/tests/ui/dyn-star/upcast.rs @@ -1,6 +1,6 @@ // known-bug: #104800 -#![feature(dyn_star, trait_upcasting)] +#![feature(dyn_star)] trait Foo: Bar { fn hello(&self); diff --git a/tests/ui/dyn-star/upcast.stderr b/tests/ui/dyn-star/upcast.stderr index 8b34c7f8b710..a7a40c801866 100644 --- a/tests/ui/dyn-star/upcast.stderr +++ b/tests/ui/dyn-star/upcast.stderr @@ -1,7 +1,7 @@ warning: the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/upcast.rs:3:12 | -LL | #![feature(dyn_star, trait_upcasting)] +LL | #![feature(dyn_star)] | ^^^^^^^^ | = note: see issue #102425 for more information diff --git a/tests/ui/feature-gates/feature-gate-trait_upcasting.rs b/tests/ui/feature-gates/feature-gate-trait_upcasting.rs deleted file mode 100644 index e4102f1cfa75..000000000000 --- a/tests/ui/feature-gates/feature-gate-trait_upcasting.rs +++ /dev/null @@ -1,13 +0,0 @@ -trait Foo {} - -trait Bar: Foo {} - -impl Foo for () {} - -impl Bar for () {} - -fn main() { - let bar: &dyn Bar = &(); - let foo: &dyn Foo = bar; - //~^ ERROR trait upcasting coercion is experimental [E0658] -} diff --git a/tests/ui/feature-gates/feature-gate-trait_upcasting.stderr b/tests/ui/feature-gates/feature-gate-trait_upcasting.stderr deleted file mode 100644 index 93afa78459d3..000000000000 --- a/tests/ui/feature-gates/feature-gate-trait_upcasting.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0658]: cannot cast `dyn Bar` to `dyn Foo`, trait upcasting coercion is experimental - --> $DIR/feature-gate-trait_upcasting.rs:11:25 - | -LL | let foo: &dyn Foo = bar; - | ^^^ - | - = note: see issue #65991 for more information - = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable - = note: required when coercing `&dyn Bar` into `&dyn Foo` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/new-solver/normalize-unsize-rhs.rs b/tests/ui/traits/new-solver/normalize-unsize-rhs.rs index a398ab4f2f2c..1bb5c9b4111a 100644 --- a/tests/ui/traits/new-solver/normalize-unsize-rhs.rs +++ b/tests/ui/traits/new-solver/normalize-unsize-rhs.rs @@ -1,8 +1,6 @@ // compile-flags: -Ztrait-solver=next // check-pass -#![feature(trait_upcasting)] - trait A {} trait B: A {} diff --git a/tests/ui/traits/new-solver/trait-upcast-lhs-needs-normalization.rs b/tests/ui/traits/new-solver/trait-upcast-lhs-needs-normalization.rs index 43cd773bf3ce..79114b93b78d 100644 --- a/tests/ui/traits/new-solver/trait-upcast-lhs-needs-normalization.rs +++ b/tests/ui/traits/new-solver/trait-upcast-lhs-needs-normalization.rs @@ -1,8 +1,6 @@ // check-pass // compile-flags: -Ztrait-solver=next -#![feature(trait_upcasting)] - pub trait A {} pub trait B: A {} diff --git a/tests/ui/traits/new-solver/upcast-right-substs.rs b/tests/ui/traits/new-solver/upcast-right-substs.rs index c19c82acf24f..97eb189d5c73 100644 --- a/tests/ui/traits/new-solver/upcast-right-substs.rs +++ b/tests/ui/traits/new-solver/upcast-right-substs.rs @@ -1,8 +1,6 @@ // compile-flags: -Ztrait-solver=next // check-pass -#![feature(trait_upcasting)] - trait Foo: Bar + Bar {} trait Bar {} diff --git a/tests/ui/traits/new-solver/upcast-wrong-substs.rs b/tests/ui/traits/new-solver/upcast-wrong-substs.rs index f2d04d932bbc..3376f9787d36 100644 --- a/tests/ui/traits/new-solver/upcast-wrong-substs.rs +++ b/tests/ui/traits/new-solver/upcast-wrong-substs.rs @@ -1,7 +1,5 @@ // compile-flags: -Ztrait-solver=next -#![feature(trait_upcasting)] - trait Foo: Bar + Bar {} trait Bar {} diff --git a/tests/ui/traits/new-solver/upcast-wrong-substs.stderr b/tests/ui/traits/new-solver/upcast-wrong-substs.stderr index 8623f395f597..7d16aaa9a16a 100644 --- a/tests/ui/traits/new-solver/upcast-wrong-substs.stderr +++ b/tests/ui/traits/new-solver/upcast-wrong-substs.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/upcast-wrong-substs.rs:11:30 + --> $DIR/upcast-wrong-substs.rs:9:30 | LL | let y: &dyn Bar = x; | --------------- ^ expected trait `Bar`, found trait `Foo` diff --git a/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.rs b/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.rs index 4a5e445d1efb..927a9d6b94f8 100644 --- a/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.rs +++ b/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.rs @@ -1,4 +1,3 @@ -#![feature(trait_upcasting)] #![feature(trait_alias)] // Although we *elaborate* `T: Alias` to `i32: B`, we should diff --git a/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.stderr b/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.stderr index 5574a0320895..c4f00c9f55fe 100644 --- a/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.stderr +++ b/tests/ui/traits/trait-upcasting/alias-where-clause-isnt-supertrait.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/alias-where-clause-isnt-supertrait.rs:27:5 + --> $DIR/alias-where-clause-isnt-supertrait.rs:26:5 | LL | fn test(x: &dyn C) -> &dyn B { | ------ expected `&dyn B` because of return type diff --git a/tests/ui/traits/trait-upcasting/basic.rs b/tests/ui/traits/trait-upcasting/basic.rs index 570ec5160bfe..538cd8329cc6 100644 --- a/tests/ui/traits/trait-upcasting/basic.rs +++ b/tests/ui/traits/trait-upcasting/basic.rs @@ -1,7 +1,5 @@ // run-pass -#![feature(trait_upcasting)] - trait Foo: PartialEq + std::fmt::Debug + Send + Sync { fn a(&self) -> i32 { 10 diff --git a/tests/ui/traits/trait-upcasting/correct-supertrait-substitution.rs b/tests/ui/traits/trait-upcasting/correct-supertrait-substitution.rs index eae5cf8d58d0..4a379d9f875b 100644 --- a/tests/ui/traits/trait-upcasting/correct-supertrait-substitution.rs +++ b/tests/ui/traits/trait-upcasting/correct-supertrait-substitution.rs @@ -1,5 +1,4 @@ // run-pass -#![feature(trait_upcasting)] trait Foo: Bar + Bar {} trait Bar { diff --git a/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.rs b/tests/ui/traits/trait-upcasting/deref-lint-regions.rs similarity index 53% rename from tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.rs rename to tests/ui/traits/trait-upcasting/deref-lint-regions.rs index b3f14a5f256e..946305cbb2b4 100644 --- a/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.rs +++ b/tests/ui/traits/trait-upcasting/deref-lint-regions.rs @@ -1,4 +1,4 @@ -#![deny(deref_into_dyn_supertrait)] +// check-pass use std::ops::Deref; @@ -6,8 +6,7 @@ trait Bar<'a> {} trait Foo<'a>: Bar<'a> {} impl<'a> Deref for dyn Foo<'a> { - //~^ ERROR dyn Foo<'_>` implements `Deref` with supertrait `Bar<'_>` as target - //~| WARN this will change its meaning in a future release! + //~^ WARN this `Deref` implementation is covered by an implicit supertrait coercion type Target = dyn Bar<'a>; fn deref(&self) -> &Self::Target { diff --git a/tests/ui/traits/trait-upcasting/deref-lint-regions.stderr b/tests/ui/traits/trait-upcasting/deref-lint-regions.stderr new file mode 100644 index 000000000000..dd4aa8e9a078 --- /dev/null +++ b/tests/ui/traits/trait-upcasting/deref-lint-regions.stderr @@ -0,0 +1,14 @@ +warning: this `Deref` implementation is covered by an implicit supertrait coercion + --> $DIR/deref-lint-regions.rs:8:1 + | +LL | impl<'a> Deref for dyn Foo<'a> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | +LL | type Target = dyn Bar<'a>; + | -------------------------- target type is a supertrait of `dyn Foo<'_>` + | + = help: consider removing this implementation or replacing it with a method instead + = note: `#[warn(deref_into_dyn_supertrait)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/trait-upcasting/migrate-lint-deny.rs b/tests/ui/traits/trait-upcasting/deref-lint.rs similarity index 60% rename from tests/ui/traits/trait-upcasting/migrate-lint-deny.rs rename to tests/ui/traits/trait-upcasting/deref-lint.rs index 114d2c249da0..dfca7b0fa68f 100644 --- a/tests/ui/traits/trait-upcasting/migrate-lint-deny.rs +++ b/tests/ui/traits/trait-upcasting/deref-lint.rs @@ -1,4 +1,4 @@ -#![deny(deref_into_dyn_supertrait)] +// check-pass use std::ops::Deref; @@ -7,9 +7,7 @@ trait A {} trait B: A {} impl<'a> Deref for dyn 'a + B { - //~^ ERROR `dyn B` implements `Deref` with supertrait `A` as target - //~| WARN this will change its meaning in a future release! - + //~^ WARN this `Deref` implementation is covered by an implicit supertrait coercion type Target = dyn A; fn deref(&self) -> &Self::Target { todo!() diff --git a/tests/ui/traits/trait-upcasting/deref-lint.stderr b/tests/ui/traits/trait-upcasting/deref-lint.stderr new file mode 100644 index 000000000000..0f7a61dfa808 --- /dev/null +++ b/tests/ui/traits/trait-upcasting/deref-lint.stderr @@ -0,0 +1,14 @@ +warning: this `Deref` implementation is covered by an implicit supertrait coercion + --> $DIR/deref-lint.rs:9:1 + | +LL | impl<'a> Deref for dyn 'a + B { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | +LL | type Target = dyn A; + | -------------------- target type is a supertrait of `dyn B` + | + = help: consider removing this implementation or replacing it with a method instead + = note: `#[warn(deref_into_dyn_supertrait)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/trait-upcasting/diamond.rs b/tests/ui/traits/trait-upcasting/diamond.rs index a4f81c464b40..9a78339a4ec8 100644 --- a/tests/ui/traits/trait-upcasting/diamond.rs +++ b/tests/ui/traits/trait-upcasting/diamond.rs @@ -1,7 +1,5 @@ // run-pass -#![feature(trait_upcasting)] - trait Foo: PartialEq + std::fmt::Debug + Send + Sync { fn a(&self) -> i32 { 10 diff --git a/tests/ui/traits/trait-upcasting/fewer-associated.rs b/tests/ui/traits/trait-upcasting/fewer-associated.rs index 8228eea2681a..937818aac58e 100644 --- a/tests/ui/traits/trait-upcasting/fewer-associated.rs +++ b/tests/ui/traits/trait-upcasting/fewer-associated.rs @@ -3,8 +3,6 @@ // revisions: current next //[next] compile-flags: -Ztrait-solver=next -#![feature(trait_upcasting)] - trait A: B { type Assoc; } diff --git a/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.current.stderr b/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.current.stderr index 59c9d5737056..a1b671b4a321 100644 --- a/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.current.stderr +++ b/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.current.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/illegal-upcast-from-impl.rs:16:66 + --> $DIR/illegal-upcast-from-impl.rs:14:66 | LL | fn illegal(x: &dyn Sub) -> &dyn Super { x } | ----------------------- ^ expected trait `Super`, found trait `Sub` diff --git a/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.next.stderr b/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.next.stderr index 59c9d5737056..a1b671b4a321 100644 --- a/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.next.stderr +++ b/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.next.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/illegal-upcast-from-impl.rs:16:66 + --> $DIR/illegal-upcast-from-impl.rs:14:66 | LL | fn illegal(x: &dyn Sub) -> &dyn Super { x } | ----------------------- ^ expected trait `Super`, found trait `Sub` diff --git a/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.rs b/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.rs index 774474281eab..4b730dab7cca 100644 --- a/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.rs +++ b/tests/ui/traits/trait-upcasting/illegal-upcast-from-impl.rs @@ -1,8 +1,6 @@ // revisions: current next //[next] compile-flags: -Ztrait-solver=next -#![feature(trait_upcasting)] - trait Super { type Assoc; } diff --git a/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.rs b/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.rs index 79fb643eacd0..999f3b16f50d 100644 --- a/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.rs +++ b/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.rs @@ -1,5 +1,4 @@ #![deny(deref_into_dyn_supertrait)] -#![feature(trait_upcasting)] // remove this and the test compiles use std::ops::Deref; diff --git a/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.stderr b/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.stderr index cfd6f7f175ff..48d331e81b0c 100644 --- a/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.stderr +++ b/tests/ui/traits/trait-upcasting/inference-behavior-change-deref.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/inference-behavior-change-deref.rs:34:18 + --> $DIR/inference-behavior-change-deref.rs:33:18 | LL | let z: u32 = y; | --- ^ expected `u32`, found `i32` diff --git a/tests/ui/traits/trait-upcasting/invalid-upcast.rs b/tests/ui/traits/trait-upcasting/invalid-upcast.rs index e634bbd5ac6f..9269a5e3e9ff 100644 --- a/tests/ui/traits/trait-upcasting/invalid-upcast.rs +++ b/tests/ui/traits/trait-upcasting/invalid-upcast.rs @@ -1,5 +1,3 @@ -#![feature(trait_upcasting)] - trait Foo { fn a(&self) -> i32 { 10 diff --git a/tests/ui/traits/trait-upcasting/invalid-upcast.stderr b/tests/ui/traits/trait-upcasting/invalid-upcast.stderr index 3aa21ee3dddf..e70b99d28c7e 100644 --- a/tests/ui/traits/trait-upcasting/invalid-upcast.stderr +++ b/tests/ui/traits/trait-upcasting/invalid-upcast.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:53:35 + --> $DIR/invalid-upcast.rs:51:35 | LL | let _: &dyn std::fmt::Debug = baz; | -------------------- ^^^ expected trait `Debug`, found trait `Baz` @@ -10,7 +10,7 @@ LL | let _: &dyn std::fmt::Debug = baz; found reference `&dyn Baz` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:55:24 + --> $DIR/invalid-upcast.rs:53:24 | LL | let _: &dyn Send = baz; | --------- ^^^ expected trait `Send`, found trait `Baz` @@ -21,7 +21,7 @@ LL | let _: &dyn Send = baz; found reference `&dyn Baz` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:57:24 + --> $DIR/invalid-upcast.rs:55:24 | LL | let _: &dyn Sync = baz; | --------- ^^^ expected trait `Sync`, found trait `Baz` @@ -32,7 +32,7 @@ LL | let _: &dyn Sync = baz; found reference `&dyn Baz` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:60:25 + --> $DIR/invalid-upcast.rs:58:25 | LL | let bar: &dyn Bar = baz; | -------- ^^^ expected trait `Bar`, found trait `Baz` @@ -43,7 +43,7 @@ LL | let bar: &dyn Bar = baz; found reference `&dyn Baz` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:62:35 + --> $DIR/invalid-upcast.rs:60:35 | LL | let _: &dyn std::fmt::Debug = bar; | -------------------- ^^^ expected trait `Debug`, found trait `Bar` @@ -54,7 +54,7 @@ LL | let _: &dyn std::fmt::Debug = bar; found reference `&dyn Bar` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:64:24 + --> $DIR/invalid-upcast.rs:62:24 | LL | let _: &dyn Send = bar; | --------- ^^^ expected trait `Send`, found trait `Bar` @@ -65,7 +65,7 @@ LL | let _: &dyn Send = bar; found reference `&dyn Bar` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:66:24 + --> $DIR/invalid-upcast.rs:64:24 | LL | let _: &dyn Sync = bar; | --------- ^^^ expected trait `Sync`, found trait `Bar` @@ -76,7 +76,7 @@ LL | let _: &dyn Sync = bar; found reference `&dyn Bar` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:69:25 + --> $DIR/invalid-upcast.rs:67:25 | LL | let foo: &dyn Foo = baz; | -------- ^^^ expected trait `Foo`, found trait `Baz` @@ -87,7 +87,7 @@ LL | let foo: &dyn Foo = baz; found reference `&dyn Baz` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:71:35 + --> $DIR/invalid-upcast.rs:69:35 | LL | let _: &dyn std::fmt::Debug = foo; | -------------------- ^^^ expected trait `Debug`, found trait `Foo` @@ -98,7 +98,7 @@ LL | let _: &dyn std::fmt::Debug = foo; found reference `&dyn Foo` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:73:24 + --> $DIR/invalid-upcast.rs:71:24 | LL | let _: &dyn Send = foo; | --------- ^^^ expected trait `Send`, found trait `Foo` @@ -109,7 +109,7 @@ LL | let _: &dyn Send = foo; found reference `&dyn Foo` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:75:24 + --> $DIR/invalid-upcast.rs:73:24 | LL | let _: &dyn Sync = foo; | --------- ^^^ expected trait `Sync`, found trait `Foo` @@ -120,7 +120,7 @@ LL | let _: &dyn Sync = foo; found reference `&dyn Foo` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:78:25 + --> $DIR/invalid-upcast.rs:76:25 | LL | let foo: &dyn Foo = bar; | -------- ^^^ expected trait `Foo`, found trait `Bar` @@ -131,7 +131,7 @@ LL | let foo: &dyn Foo = bar; found reference `&dyn Bar` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:80:35 + --> $DIR/invalid-upcast.rs:78:35 | LL | let _: &dyn std::fmt::Debug = foo; | -------------------- ^^^ expected trait `Debug`, found trait `Foo` @@ -142,7 +142,7 @@ LL | let _: &dyn std::fmt::Debug = foo; found reference `&dyn Foo` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:82:24 + --> $DIR/invalid-upcast.rs:80:24 | LL | let _: &dyn Send = foo; | --------- ^^^ expected trait `Send`, found trait `Foo` @@ -153,7 +153,7 @@ LL | let _: &dyn Send = foo; found reference `&dyn Foo` error[E0308]: mismatched types - --> $DIR/invalid-upcast.rs:84:24 + --> $DIR/invalid-upcast.rs:82:24 | LL | let _: &dyn Sync = foo; | --------- ^^^ expected trait `Sync`, found trait `Foo` diff --git a/tests/ui/traits/trait-upcasting/issue-11515-upcast-fn_mut-fn.rs b/tests/ui/traits/trait-upcasting/issue-11515-upcast-fn_mut-fn.rs index b672963ae988..77ce627078f9 100644 --- a/tests/ui/traits/trait-upcasting/issue-11515-upcast-fn_mut-fn.rs +++ b/tests/ui/traits/trait-upcasting/issue-11515-upcast-fn_mut-fn.rs @@ -1,5 +1,4 @@ // run-pass -#![feature(trait_upcasting)] struct Test { func: Box, diff --git a/tests/ui/traits/trait-upcasting/issue-11515.current.stderr b/tests/ui/traits/trait-upcasting/issue-11515.current.stderr deleted file mode 100644 index 97d66cccb25b..000000000000 --- a/tests/ui/traits/trait-upcasting/issue-11515.current.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0658]: cannot cast `dyn Fn()` to `dyn FnMut()`, trait upcasting coercion is experimental - --> $DIR/issue-11515.rs:10:38 - | -LL | let test = Box::new(Test { func: closure }); - | ^^^^^^^ - | - = note: see issue #65991 for more information - = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable - = note: required when coercing `Box<(dyn Fn() + 'static)>` into `Box<(dyn FnMut() + 'static)>` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/trait-upcasting/issue-11515.next.stderr b/tests/ui/traits/trait-upcasting/issue-11515.next.stderr deleted file mode 100644 index 97d66cccb25b..000000000000 --- a/tests/ui/traits/trait-upcasting/issue-11515.next.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0658]: cannot cast `dyn Fn()` to `dyn FnMut()`, trait upcasting coercion is experimental - --> $DIR/issue-11515.rs:10:38 - | -LL | let test = Box::new(Test { func: closure }); - | ^^^^^^^ - | - = note: see issue #65991 for more information - = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable - = note: required when coercing `Box<(dyn Fn() + 'static)>` into `Box<(dyn FnMut() + 'static)>` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/trait-upcasting/issue-11515.rs b/tests/ui/traits/trait-upcasting/issue-11515.rs index 723f3a24fd4e..66ab1ce260a4 100644 --- a/tests/ui/traits/trait-upcasting/issue-11515.rs +++ b/tests/ui/traits/trait-upcasting/issue-11515.rs @@ -1,3 +1,4 @@ +// check-pass // revisions: current next //[next] compile-flags: -Ztrait-solver=next @@ -7,5 +8,5 @@ struct Test { fn main() { let closure: Box = Box::new(|| ()); - let test = Box::new(Test { func: closure }); //~ ERROR trait upcasting coercion is experimental [E0658] + let test = Box::new(Test { func: closure }); } diff --git a/tests/ui/traits/trait-upcasting/lifetime.rs b/tests/ui/traits/trait-upcasting/lifetime.rs index 9825158c2dd3..6c65c38870f2 100644 --- a/tests/ui/traits/trait-upcasting/lifetime.rs +++ b/tests/ui/traits/trait-upcasting/lifetime.rs @@ -1,7 +1,5 @@ // run-pass -#![feature(trait_upcasting)] - trait Foo: PartialEq + std::fmt::Debug + Send + Sync { fn a(&self) -> i32 { 10 diff --git a/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr b/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr deleted file mode 100644 index 250bcabc6982..000000000000 --- a/tests/ui/traits/trait-upcasting/migrate-lint-deny-regions.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error: `dyn Foo<'_>` implements `Deref` with supertrait `Bar<'_>` as target - --> $DIR/migrate-lint-deny-regions.rs:8:1 - | -LL | impl<'a> Deref for dyn Foo<'a> { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | type Target = dyn Bar<'a>; - | -------------------------- target type is set here - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #89460 -note: the lint level is defined here - --> $DIR/migrate-lint-deny-regions.rs:1:9 - | -LL | #![deny(deref_into_dyn_supertrait)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to previous error - diff --git a/tests/ui/traits/trait-upcasting/migrate-lint-deny.stderr b/tests/ui/traits/trait-upcasting/migrate-lint-deny.stderr deleted file mode 100644 index c8b683c23c18..000000000000 --- a/tests/ui/traits/trait-upcasting/migrate-lint-deny.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error: `dyn B` implements `Deref` with supertrait `A` as target - --> $DIR/migrate-lint-deny.rs:9:1 - | -LL | impl<'a> Deref for dyn 'a + B { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | type Target = dyn A; - | -------------------- target type is set here - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #89460 -note: the lint level is defined here - --> $DIR/migrate-lint-deny.rs:1:9 - | -LL | #![deny(deref_into_dyn_supertrait)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to previous error - diff --git a/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.rs b/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.rs index 2e53a00a90e9..0e17c2767177 100644 --- a/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.rs +++ b/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.rs @@ -1,5 +1,4 @@ // check-fail -#![feature(trait_upcasting)] trait Bar { fn bar(&self, _: T) {} diff --git a/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.stderr b/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.stderr index 0ad18be03cdf..ea44a81e2a7f 100644 --- a/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.stderr +++ b/tests/ui/traits/trait-upcasting/multiple-occurrence-ambiguousity.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/multiple-occurrence-ambiguousity.rs:20:26 + --> $DIR/multiple-occurrence-ambiguousity.rs:19:26 | LL | let t: &dyn Bar<_> = s; | ----------- ^ expected trait `Bar`, found trait `Foo` diff --git a/tests/ui/traits/trait-upcasting/normalization.rs b/tests/ui/traits/trait-upcasting/normalization.rs index c78338b0da93..c57640e7e346 100644 --- a/tests/ui/traits/trait-upcasting/normalization.rs +++ b/tests/ui/traits/trait-upcasting/normalization.rs @@ -3,8 +3,6 @@ // revisions: current next //[next] compile-flags: -Ztrait-solver=next -#![feature(trait_upcasting)] - trait Mirror { type Assoc; } diff --git a/tests/ui/traits/trait-upcasting/replace-vptr.rs b/tests/ui/traits/trait-upcasting/replace-vptr.rs index 9ccfc9306ac0..4a7304ec2d71 100644 --- a/tests/ui/traits/trait-upcasting/replace-vptr.rs +++ b/tests/ui/traits/trait-upcasting/replace-vptr.rs @@ -1,7 +1,5 @@ // run-pass -#![feature(trait_upcasting)] - trait A { fn foo_a(&self); } diff --git a/tests/ui/traits/trait-upcasting/struct.rs b/tests/ui/traits/trait-upcasting/struct.rs index a3e41696956c..64fa9ca1b5fa 100644 --- a/tests/ui/traits/trait-upcasting/struct.rs +++ b/tests/ui/traits/trait-upcasting/struct.rs @@ -1,7 +1,5 @@ // run-pass -#![feature(trait_upcasting)] - use std::rc::Rc; use std::sync::Arc; diff --git a/tests/ui/traits/trait-upcasting/subtrait-method.rs b/tests/ui/traits/trait-upcasting/subtrait-method.rs index 136d15af0e8b..20277280440c 100644 --- a/tests/ui/traits/trait-upcasting/subtrait-method.rs +++ b/tests/ui/traits/trait-upcasting/subtrait-method.rs @@ -1,5 +1,3 @@ -#![feature(trait_upcasting)] - trait Foo: PartialEq + std::fmt::Debug + Send + Sync { fn a(&self) -> i32 { 10 diff --git a/tests/ui/traits/trait-upcasting/subtrait-method.stderr b/tests/ui/traits/trait-upcasting/subtrait-method.stderr index 918159e845b9..3fdf3f481616 100644 --- a/tests/ui/traits/trait-upcasting/subtrait-method.stderr +++ b/tests/ui/traits/trait-upcasting/subtrait-method.stderr @@ -1,64 +1,64 @@ error[E0599]: no method named `c` found for reference `&dyn Bar` in the current scope - --> $DIR/subtrait-method.rs:55:9 + --> $DIR/subtrait-method.rs:53:9 | LL | bar.c(); | ^ help: there is a method with a similar name: `a` | = help: items from traits can only be used if the trait is implemented and in scope note: `Baz` defines an item `c`, perhaps you need to implement it - --> $DIR/subtrait-method.rs:27:1 + --> $DIR/subtrait-method.rs:25:1 | LL | trait Baz: Bar { | ^^^^^^^^^^^^^^ error[E0599]: no method named `b` found for reference `&dyn Foo` in the current scope + --> $DIR/subtrait-method.rs:57:9 + | +LL | foo.b(); + | ^ help: there is a method with a similar name: `a` + | + = help: items from traits can only be used if the trait is implemented and in scope +note: `Bar` defines an item `b`, perhaps you need to implement it + --> $DIR/subtrait-method.rs:15:1 + | +LL | trait Bar: Foo { + | ^^^^^^^^^^^^^^ + +error[E0599]: no method named `c` found for reference `&dyn Foo` in the current scope --> $DIR/subtrait-method.rs:59:9 | -LL | foo.b(); - | ^ help: there is a method with a similar name: `a` - | - = help: items from traits can only be used if the trait is implemented and in scope -note: `Bar` defines an item `b`, perhaps you need to implement it - --> $DIR/subtrait-method.rs:17:1 - | -LL | trait Bar: Foo { - | ^^^^^^^^^^^^^^ - -error[E0599]: no method named `c` found for reference `&dyn Foo` in the current scope - --> $DIR/subtrait-method.rs:61:9 - | LL | foo.c(); | ^ help: there is a method with a similar name: `a` | = help: items from traits can only be used if the trait is implemented and in scope note: `Baz` defines an item `c`, perhaps you need to implement it - --> $DIR/subtrait-method.rs:27:1 + --> $DIR/subtrait-method.rs:25:1 | LL | trait Baz: Bar { | ^^^^^^^^^^^^^^ error[E0599]: no method named `b` found for reference `&dyn Foo` in the current scope - --> $DIR/subtrait-method.rs:65:9 + --> $DIR/subtrait-method.rs:63:9 | LL | foo.b(); | ^ help: there is a method with a similar name: `a` | = help: items from traits can only be used if the trait is implemented and in scope note: `Bar` defines an item `b`, perhaps you need to implement it - --> $DIR/subtrait-method.rs:17:1 + --> $DIR/subtrait-method.rs:15:1 | LL | trait Bar: Foo { | ^^^^^^^^^^^^^^ error[E0599]: no method named `c` found for reference `&dyn Foo` in the current scope - --> $DIR/subtrait-method.rs:67:9 + --> $DIR/subtrait-method.rs:65:9 | LL | foo.c(); | ^ help: there is a method with a similar name: `a` | = help: items from traits can only be used if the trait is implemented and in scope note: `Baz` defines an item `c`, perhaps you need to implement it - --> $DIR/subtrait-method.rs:27:1 + --> $DIR/subtrait-method.rs:25:1 | LL | trait Baz: Bar { | ^^^^^^^^^^^^^^ diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-1.current.stderr b/tests/ui/traits/trait-upcasting/type-checking-test-1.current.stderr index b612005fcb05..bcba37cab784 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-1.current.stderr +++ b/tests/ui/traits/trait-upcasting/type-checking-test-1.current.stderr @@ -1,5 +1,5 @@ error[E0605]: non-primitive cast: `&dyn Foo` as `&dyn Bar<_>` - --> $DIR/type-checking-test-1.rs:19:13 + --> $DIR/type-checking-test-1.rs:17:13 | LL | let _ = x as &dyn Bar<_>; // Ambiguous | ^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-1.next.stderr b/tests/ui/traits/trait-upcasting/type-checking-test-1.next.stderr index b612005fcb05..bcba37cab784 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-1.next.stderr +++ b/tests/ui/traits/trait-upcasting/type-checking-test-1.next.stderr @@ -1,5 +1,5 @@ error[E0605]: non-primitive cast: `&dyn Foo` as `&dyn Bar<_>` - --> $DIR/type-checking-test-1.rs:19:13 + --> $DIR/type-checking-test-1.rs:17:13 | LL | let _ = x as &dyn Bar<_>; // Ambiguous | ^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-1.rs b/tests/ui/traits/trait-upcasting/type-checking-test-1.rs index afea8521e87d..3b6ec3b65e75 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-1.rs +++ b/tests/ui/traits/trait-upcasting/type-checking-test-1.rs @@ -1,8 +1,6 @@ // revisions: current next //[next] compile-flags: -Ztrait-solver=next -#![feature(trait_upcasting)] - trait Foo: Bar + Bar {} trait Bar { fn bar(&self) -> Option { diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-2.rs b/tests/ui/traits/trait-upcasting/type-checking-test-2.rs index b024b27750bc..b4df0f5a9025 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-2.rs +++ b/tests/ui/traits/trait-upcasting/type-checking-test-2.rs @@ -1,5 +1,3 @@ -#![feature(trait_upcasting)] - trait Foo: Bar + Bar {} trait Bar { fn bar(&self) -> Option { diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-2.stderr b/tests/ui/traits/trait-upcasting/type-checking-test-2.stderr index 3e59b9d33634..f84ea93dc679 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-2.stderr +++ b/tests/ui/traits/trait-upcasting/type-checking-test-2.stderr @@ -1,11 +1,11 @@ error[E0605]: non-primitive cast: `&dyn Foo` as `&dyn Bar` - --> $DIR/type-checking-test-2.rs:19:13 + --> $DIR/type-checking-test-2.rs:17:13 | LL | let _ = x as &dyn Bar; // Error | ^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object error[E0605]: non-primitive cast: `&dyn Foo` as `&dyn Bar<_>` - --> $DIR/type-checking-test-2.rs:24:13 + --> $DIR/type-checking-test-2.rs:22:13 | LL | let a = x as &dyn Bar<_>; // Ambiguous | ^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-3.rs b/tests/ui/traits/trait-upcasting/type-checking-test-3.rs index b2db3a127974..3685569d98d1 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-3.rs +++ b/tests/ui/traits/trait-upcasting/type-checking-test-3.rs @@ -1,5 +1,3 @@ -#![feature(trait_upcasting)] - trait Foo<'a>: Bar<'a> {} trait Bar<'a> {} diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr b/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr index e6cb6a753998..640a6066268d 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr +++ b/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr @@ -1,5 +1,5 @@ error: lifetime may not live long enough - --> $DIR/type-checking-test-3.rs:11:13 + --> $DIR/type-checking-test-3.rs:9:13 | LL | fn test_wrong1<'a>(x: &dyn Foo<'static>, y: &'a u32) { | -- lifetime `'a` defined here @@ -7,7 +7,7 @@ LL | let _ = x as &dyn Bar<'a>; // Error | ^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-3.rs:16:13 + --> $DIR/type-checking-test-3.rs:14:13 | LL | fn test_wrong2<'a>(x: &dyn Foo<'a>) { | -- lifetime `'a` defined here diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-4.rs b/tests/ui/traits/trait-upcasting/type-checking-test-4.rs index f40c48f0d125..65391502386d 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-4.rs +++ b/tests/ui/traits/trait-upcasting/type-checking-test-4.rs @@ -1,5 +1,3 @@ -#![feature(trait_upcasting)] - trait Foo<'a>: Bar<'a, 'a> {} trait Bar<'a, 'b> { fn get_b(&self) -> Option<&'a u32> { diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr b/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr index 8d506e5807ec..7e7548955d39 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr +++ b/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr @@ -1,5 +1,5 @@ error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:15:13 + --> $DIR/type-checking-test-4.rs:13:13 | LL | fn test_wrong1<'a>(x: &dyn Foo<'static>, y: &'a u32) { | -- lifetime `'a` defined here @@ -7,7 +7,7 @@ LL | let _ = x as &dyn Bar<'static, 'a>; // Error | ^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:20:13 + --> $DIR/type-checking-test-4.rs:18:13 | LL | fn test_wrong2<'a>(x: &dyn Foo<'static>, y: &'a u32) { | -- lifetime `'a` defined here @@ -15,7 +15,7 @@ LL | let _ = x as &dyn Bar<'a, 'static>; // Error | ^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:26:5 + --> $DIR/type-checking-test-4.rs:24:5 | LL | fn test_wrong3<'a>(x: &dyn Foo<'a>) -> Option<&'static u32> { | -- lifetime `'a` defined here @@ -24,7 +24,7 @@ LL | y.get_b() // ERROR | ^^^^^^^^^ returning this value requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:31:5 + --> $DIR/type-checking-test-4.rs:29:5 | LL | fn test_wrong4<'a>(x: &dyn Foo<'a>) -> Option<&'static u32> { | -- lifetime `'a` defined here @@ -32,7 +32,7 @@ LL | <_ as Bar>::get_b(x) // ERROR | ^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:36:5 + --> $DIR/type-checking-test-4.rs:34:5 | LL | fn test_wrong5<'a>(x: &dyn Foo<'a>) -> Option<&'static u32> { | -- lifetime `'a` defined here @@ -40,7 +40,7 @@ LL | <_ as Bar<'_, '_>>::get_b(x) // ERROR | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:44:5 + --> $DIR/type-checking-test-4.rs:42:5 | LL | fn test_wrong6<'a>(x: &dyn Foo<'a>) -> Option<&'static u32> { | -- lifetime `'a` defined here diff --git a/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.current.stderr b/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.current.stderr deleted file mode 100644 index 9f0993d65a71..000000000000 --- a/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.current.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0658]: cannot cast `dyn A` to `dyn B`, trait upcasting coercion is experimental - --> $DIR/upcast-through-struct-tail.rs:10:5 - | -LL | x - | ^ - | - = note: see issue #65991 for more information - = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable - = note: required when coercing `Box>` into `Box>` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.next.stderr b/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.next.stderr deleted file mode 100644 index 9f0993d65a71..000000000000 --- a/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.next.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0658]: cannot cast `dyn A` to `dyn B`, trait upcasting coercion is experimental - --> $DIR/upcast-through-struct-tail.rs:10:5 - | -LL | x - | ^ - | - = note: see issue #65991 for more information - = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable - = note: required when coercing `Box>` into `Box>` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.rs b/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.rs index 42495f45f8a6..9981d4360629 100644 --- a/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.rs +++ b/tests/ui/traits/trait-upcasting/upcast-through-struct-tail.rs @@ -1,3 +1,4 @@ +// check-pass // revisions: current next //[next] compile-flags: -Ztrait-solver=next @@ -8,7 +9,6 @@ trait B {} fn test<'a>(x: Box>) -> Box> { x - //~^ ERROR cannot cast `dyn A` to `dyn B`, trait upcasting coercion is experimental } fn main() {} From 533de2bc4159ed929eb03f35f77b7da58311e82f Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Wed, 22 Nov 2023 12:59:22 +0000 Subject: [PATCH 49/66] needless_return unneeded `return` statement --- library/std/src/sys/windows/stdio.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/stdio.rs b/library/std/src/sys/windows/stdio.rs index a9ff909aa679..51a1a4875bbe 100644 --- a/library/std/src/sys/windows/stdio.rs +++ b/library/std/src/sys/windows/stdio.rs @@ -266,7 +266,7 @@ impl io::Read for Stdin { let mut bytes_copied = self.incomplete_utf8.read(buf); if bytes_copied == buf.len() { - return Ok(bytes_copied); + Ok(bytes_copied) } else if buf.len() - bytes_copied < 4 { // Not enough space to get a UTF-8 byte. We will use the incomplete UTF8. let mut utf16_buf = [MaybeUninit::new(0); 1]; From 6c22e57c39b8fd8304ad317b42ddb7561000215f Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:02:09 +0000 Subject: [PATCH 50/66] useless_conversion --- library/std/src/os/windows/io/handle.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/os/windows/io/handle.rs b/library/std/src/os/windows/io/handle.rs index 274af08a3881..b0540872c0b6 100644 --- a/library/std/src/os/windows/io/handle.rs +++ b/library/std/src/os/windows/io/handle.rs @@ -504,7 +504,7 @@ impl AsHandle for fs::File { impl From for OwnedHandle { #[inline] fn from(file: fs::File) -> OwnedHandle { - file.into_inner().into_inner().into_inner().into() + file.into_inner().into_inner().into_inner() } } From bfbeb3ebd977997233f93c5cce11bbdfdd34237d Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:06:35 +0000 Subject: [PATCH 51/66] unnecessary_mut_passed This is where our Windows API bindings previously (and incorrectly) used `*mut` instead of `*const` pointers. Now that the bindings have been corrected, the mutable references (which auto-convert to `*mut`) are unnecessary and we can use shared references. --- library/std/src/os/windows/io/socket.rs | 4 ++-- library/std/src/sys/windows/fs.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/std/src/os/windows/io/socket.rs b/library/std/src/os/windows/io/socket.rs index c80b9e28499b..65f161f32e75 100644 --- a/library/std/src/os/windows/io/socket.rs +++ b/library/std/src/os/windows/io/socket.rs @@ -127,7 +127,7 @@ impl BorrowedSocket<'_> { info.iAddressFamily, info.iSocketType, info.iProtocol, - &mut info, + &info, 0, sys::c::WSA_FLAG_OVERLAPPED | sys::c::WSA_FLAG_NO_HANDLE_INHERIT, ) @@ -147,7 +147,7 @@ impl BorrowedSocket<'_> { info.iAddressFamily, info.iSocketType, info.iProtocol, - &mut info, + &info, 0, sys::c::WSA_FLAG_OVERLAPPED, ) diff --git a/library/std/src/sys/windows/fs.rs b/library/std/src/sys/windows/fs.rs index d7e36b9a3fff..4deda6d97c4f 100644 --- a/library/std/src/sys/windows/fs.rs +++ b/library/std/src/sys/windows/fs.rs @@ -786,7 +786,7 @@ fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result< // tricked into following a symlink. However, it may not be available in // earlier versions of Windows. static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE); - let mut object = c::OBJECT_ATTRIBUTES { + let object = c::OBJECT_ATTRIBUTES { ObjectName: &mut name_str, RootDirectory: parent.as_raw_handle(), Attributes: ATTRIBUTES.load(Ordering::Relaxed), @@ -795,7 +795,7 @@ fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result< let status = c::NtCreateFile( &mut handle, access, - &mut object, + &object, &mut io_status, crate::ptr::null_mut(), 0, From fe255695f9ceb2417350d4d355ce35bfe5ad695b Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:17:29 +0000 Subject: [PATCH 52/66] manual_slice_size_calculation --- library/std/src/sys/windows/c.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/c.rs b/library/std/src/sys/windows/c.rs index ede04abf105f..351ec2a48be4 100644 --- a/library/std/src/sys/windows/c.rs +++ b/library/std/src/sys/windows/c.rs @@ -82,7 +82,7 @@ pub fn nt_success(status: NTSTATUS) -> bool { impl UNICODE_STRING { pub fn from_ref(slice: &[u16]) -> Self { - let len = slice.len() * mem::size_of::(); + let len = mem::size_of_val(slice); Self { Length: len as _, MaximumLength: len as _, Buffer: slice.as_ptr() as _ } } } From 42734599bd613efee41d0a508e0fc60ea6d86058 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:21:56 +0000 Subject: [PATCH 53/66] needless_borrows_for_generic_args the borrowed expression implements the required traits --- library/std/src/sys/windows/fs.rs | 2 +- library/std/src/sys/windows/process.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/sys/windows/fs.rs b/library/std/src/sys/windows/fs.rs index 4deda6d97c4f..a0d3401a0a63 100644 --- a/library/std/src/sys/windows/fs.rs +++ b/library/std/src/sys/windows/fs.rs @@ -156,7 +156,7 @@ impl DirEntry { } pub fn path(&self) -> PathBuf { - self.root.join(&self.file_name()) + self.root.join(self.file_name()) } pub fn file_name(&self) -> OsString { diff --git a/library/std/src/sys/windows/process.rs b/library/std/src/sys/windows/process.rs index f4078d359448..f7e87a6734d5 100644 --- a/library/std/src/sys/windows/process.rs +++ b/library/std/src/sys/windows/process.rs @@ -463,7 +463,7 @@ fn resolve_exe<'a>( // Search the directories given by `search_paths`. let result = search_paths(parent_paths, child_paths, |mut path| { - path.push(&exe_path); + path.push(exe_path); if !has_extension { path.set_extension(EXE_EXTENSION); } From 24542639aa6c72c1a6a3beb8275533b33b0687be Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:32:13 +0000 Subject: [PATCH 54/66] needless_borrow this expression creates a reference which is immediately dereferenced by the compiler --- library/std/src/sys/windows/fs.rs | 8 ++++---- library/std/src/sys/windows/handle.rs | 4 ++-- library/std/src/sys/windows/mod.rs | 2 +- library/std/src/sys/windows/stdio.rs | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/library/std/src/sys/windows/fs.rs b/library/std/src/sys/windows/fs.rs index a0d3401a0a63..f57034cc8d58 100644 --- a/library/std/src/sys/windows/fs.rs +++ b/library/std/src/sys/windows/fs.rs @@ -548,7 +548,7 @@ impl File { let user = super::args::from_wide_to_user_path( subst.iter().copied().chain([0]).collect(), )?; - Ok(PathBuf::from(OsString::from_wide(&user.strip_suffix(&[0]).unwrap_or(&user)))) + Ok(PathBuf::from(OsString::from_wide(user.strip_suffix(&[0]).unwrap_or(&user)))) } else { Ok(PathBuf::from(OsString::from_wide(subst))) } @@ -874,7 +874,7 @@ impl fmt::Debug for File { // FIXME(#24570): add more info here (e.g., mode) let mut b = f.debug_struct("File"); b.field("handle", &self.handle.as_raw_handle()); - if let Ok(path) = get_path(&self) { + if let Ok(path) = get_path(self) { b.field("path", &path); } b.finish() @@ -1193,7 +1193,7 @@ pub fn readlink(path: &Path) -> io::Result { let mut opts = OpenOptions::new(); opts.access_mode(0); opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS); - let file = File::open(&path, &opts)?; + let file = File::open(path, &opts)?; file.readlink() } @@ -1407,7 +1407,7 @@ pub fn symlink_junction, Q: AsRef>( #[allow(dead_code)] fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> { let d = DirBuilder::new(); - d.mkdir(&junction)?; + d.mkdir(junction)?; let mut opts = OpenOptions::new(); opts.write(true); diff --git a/library/std/src/sys/windows/handle.rs b/library/std/src/sys/windows/handle.rs index 56d0d6c08873..7badf8fea07e 100644 --- a/library/std/src/sys/windows/handle.rs +++ b/library/std/src/sys/windows/handle.rs @@ -189,7 +189,7 @@ impl Handle { } pub fn write(&self, buf: &[u8]) -> io::Result { - self.synchronous_write(&buf, None) + self.synchronous_write(buf, None) } pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { @@ -202,7 +202,7 @@ impl Handle { } pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result { - self.synchronous_write(&buf, Some(offset)) + self.synchronous_write(buf, Some(offset)) } pub fn try_clone(&self) -> io::Result { diff --git a/library/std/src/sys/windows/mod.rs b/library/std/src/sys/windows/mod.rs index c4e56e13be32..14e34ffec4d2 100644 --- a/library/std/src/sys/windows/mod.rs +++ b/library/std/src/sys/windows/mod.rs @@ -63,7 +63,7 @@ pub unsafe fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) { // Normally, `thread::spawn` will call `Thread::set_name` but since this thread already // exists, we have to call it ourselves. - thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0")); + thread::Thread::set_name(CStr::from_bytes_with_nul_unchecked(b"main\0")); } // SAFETY: must be called only once during runtime cleanup. diff --git a/library/std/src/sys/windows/stdio.rs b/library/std/src/sys/windows/stdio.rs index 51a1a4875bbe..1765c221543a 100644 --- a/library/std/src/sys/windows/stdio.rs +++ b/library/std/src/sys/windows/stdio.rs @@ -195,7 +195,7 @@ fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result Date: Tue, 21 Nov 2023 23:40:46 +0000 Subject: [PATCH 55/66] unnecessary_cast casting to the same type is unnecessary --- library/std/src/sys/windows/handle.rs | 6 +++--- library/std/src/sys/windows/io.rs | 6 +++--- library/std/src/sys/windows/os.rs | 2 +- library/std/src/sys/windows/process.rs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/library/std/src/sys/windows/handle.rs b/library/std/src/sys/windows/handle.rs index 7badf8fea07e..c4495f81a5a3 100644 --- a/library/std/src/sys/windows/handle.rs +++ b/library/std/src/sys/windows/handle.rs @@ -81,7 +81,7 @@ impl Handle { let res = unsafe { self.synchronous_read(buf.as_mut_ptr().cast(), buf.len(), None) }; match res { - Ok(read) => Ok(read as usize), + Ok(read) => Ok(read), // The special treatment of BrokenPipe is to deal with Windows // pipe semantics, which yields this error when *reading* from @@ -107,7 +107,7 @@ impl Handle { unsafe { self.synchronous_read(buf.as_mut_ptr().cast(), buf.len(), Some(offset)) }; match res { - Ok(read) => Ok(read as usize), + Ok(read) => Ok(read), Err(ref e) if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32) => Ok(0), Err(e) => Err(e), } @@ -121,7 +121,7 @@ impl Handle { Ok(read) => { // Safety: `read` bytes were written to the initialized portion of the buffer unsafe { - cursor.advance(read as usize); + cursor.advance(read); } Ok(()) } diff --git a/library/std/src/sys/windows/io.rs b/library/std/src/sys/windows/io.rs index 9b540ee071f4..649826d25cef 100644 --- a/library/std/src/sys/windows/io.rs +++ b/library/std/src/sys/windows/io.rs @@ -36,7 +36,7 @@ impl<'a> IoSlice<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) } + unsafe { slice::from_raw_parts(self.vec.buf, self.vec.len as usize) } } } @@ -70,12 +70,12 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) } + unsafe { slice::from_raw_parts(self.vec.buf, self.vec.len as usize) } } #[inline] pub fn as_mut_slice(&mut self) -> &mut [u8] { - unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize) } + unsafe { slice::from_raw_parts_mut(self.vec.buf, self.vec.len as usize) } } } diff --git a/library/std/src/sys/windows/os.rs b/library/std/src/sys/windows/os.rs index 8cc905101de7..b60fa941cb0f 100644 --- a/library/std/src/sys/windows/os.rs +++ b/library/std/src/sys/windows/os.rs @@ -364,5 +364,5 @@ pub fn exit(code: i32) -> ! { } pub fn getpid() -> u32 { - unsafe { c::GetCurrentProcessId() as u32 } + unsafe { c::GetCurrentProcessId() } } diff --git a/library/std/src/sys/windows/process.rs b/library/std/src/sys/windows/process.rs index f7e87a6734d5..a1978d71d0bc 100644 --- a/library/std/src/sys/windows/process.rs +++ b/library/std/src/sys/windows/process.rs @@ -657,7 +657,7 @@ impl Process { } pub fn id(&self) -> u32 { - unsafe { c::GetProcessId(self.handle.as_raw_handle()) as u32 } + unsafe { c::GetProcessId(self.handle.as_raw_handle()) } } pub fn main_thread_handle(&self) -> BorrowedHandle<'_> { @@ -918,7 +918,7 @@ fn make_proc_thread_attribute_list( }; let mut proc_thread_attribute_list = ProcThreadAttributeList( - vec![MaybeUninit::uninit(); required_size as usize].into_boxed_slice(), + vec![MaybeUninit::uninit(); required_size].into_boxed_slice(), ); // Once we've allocated the necessary memory, it's safe to invoke From b962ae132440dd88b9795313b2bddf161d9abb52 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:42:51 +0000 Subject: [PATCH 56/66] duration_subsec calling `subsec_micros()` is more concise than this calculation --- library/std/src/sys/windows/net.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/net.rs b/library/std/src/sys/windows/net.rs index c29b863665f1..6cd758ec5c32 100644 --- a/library/std/src/sys/windows/net.rs +++ b/library/std/src/sys/windows/net.rs @@ -162,7 +162,7 @@ impl Socket { let mut timeout = c::timeval { tv_sec: cmp::min(timeout.as_secs(), c_long::MAX as u64) as c_long, - tv_usec: (timeout.subsec_nanos() / 1000) as c_long, + tv_usec: timeout.subsec_micros() as c_long, }; if timeout.tv_sec == 0 && timeout.tv_usec == 0 { From 220217af135198ed950133f9785d93df1d49097c Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:45:52 +0000 Subject: [PATCH 57/66] redundant_closure --- library/std/src/sys/windows/api.rs | 2 +- library/std/src/sys/windows/os.rs | 4 ++-- library/std/src/sys/windows/process.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/std/src/sys/windows/api.rs b/library/std/src/sys/windows/api.rs index e9f0bbfbe2e7..72ecb9503410 100644 --- a/library/std/src/sys/windows/api.rs +++ b/library/std/src/sys/windows/api.rs @@ -132,7 +132,7 @@ pub fn set_file_information_by_handle( size: u32, ) -> Result<(), WinError> { let result = c::SetFileInformationByHandle(handle, class, info, size); - (result != 0).then_some(()).ok_or_else(|| get_last_error()) + (result != 0).then_some(()).ok_or_else(get_last_error) } // SAFETY: The `SetFileInformation` trait ensures that this is safe. unsafe { set_info(handle, T::CLASS, info.as_ptr(), info.size()) } diff --git a/library/std/src/sys/windows/os.rs b/library/std/src/sys/windows/os.rs index b60fa941cb0f..829dd5eb97ac 100644 --- a/library/std/src/sys/windows/os.rs +++ b/library/std/src/sys/windows/os.rs @@ -297,7 +297,7 @@ pub fn getenv(k: &OsStr) -> Option { let k = to_u16s(k).ok()?; super::fill_utf16_buf( |buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, - |buf| OsStringExt::from_wide(buf), + OsStringExt::from_wide, ) .ok() } @@ -356,7 +356,7 @@ pub fn home_dir() -> Option { crate::env::var_os("HOME") .or_else(|| crate::env::var_os("USERPROFILE")) .map(PathBuf::from) - .or_else(|| home_dir_crt()) + .or_else(home_dir_crt) } pub fn exit(code: i32) -> ! { diff --git a/library/std/src/sys/windows/process.rs b/library/std/src/sys/windows/process.rs index a1978d71d0bc..8a442ca4acf7 100644 --- a/library/std/src/sys/windows/process.rs +++ b/library/std/src/sys/windows/process.rs @@ -245,7 +245,7 @@ impl Command { } pub fn get_current_dir(&self) -> Option<&Path> { - self.cwd.as_ref().map(|cwd| Path::new(cwd)) + self.cwd.as_ref().map(Path::new) } pub unsafe fn raw_attribute( From 8c85c5b7f43ac4dd9bb9e444fdb89ca826b1f00e Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:48:59 +0000 Subject: [PATCH 58/66] unnecessary_lazy_evaluations unnecessary closure used with `bool::then` --- library/std/src/sys/windows/path.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/path.rs b/library/std/src/sys/windows/path.rs index f7f9f96ba5d7..5da7de5de24b 100644 --- a/library/std/src/sys/windows/path.rs +++ b/library/std/src/sys/windows/path.rs @@ -78,7 +78,7 @@ impl<'a> PrefixParserSlice<'a, '_> { fn strip_prefix(&self, prefix: &str) -> Option { self.prefix[self.index..] .starts_with(prefix.as_bytes()) - .then(|| Self { index: self.index + prefix.len(), ..*self }) + .then_some(Self { index: self.index + prefix.len(), ..*self }) } fn prefix_bytes(&self) -> &'a [u8] { From 4c084c576ac5de81164a0d6a44093d99f47c233f Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:55:07 +0000 Subject: [PATCH 59/66] manual_map manual implementation of `Option::map` --- library/std/src/sys/windows/path.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/library/std/src/sys/windows/path.rs b/library/std/src/sys/windows/path.rs index 5da7de5de24b..6f62206532cc 100644 --- a/library/std/src/sys/windows/path.rs +++ b/library/std/src/sys/windows/path.rs @@ -147,12 +147,10 @@ pub fn parse_prefix(path: &OsStr) -> Option> { None } } - } else if let Some(drive) = parse_drive(path) { - // C: - Some(Disk(drive)) } else { - // no prefix - None + // If it has a drive like `C:` then it's a disk. + // Otherwise there is no prefix. + parse_drive(path).map(Disk) } } From d7e1f1cc0813727b197e13a7672517da7ff42b44 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 21 Nov 2023 23:57:11 +0000 Subject: [PATCH 60/66] op_ref taken reference of right operand --- library/std/src/sys/windows/path.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/path.rs b/library/std/src/sys/windows/path.rs index 6f62206532cc..d9684f217531 100644 --- a/library/std/src/sys/windows/path.rs +++ b/library/std/src/sys/windows/path.rs @@ -250,7 +250,7 @@ pub(crate) fn get_long_path(mut path: Vec, prefer_verbatim: bool) -> io::Re // \\?\UNC\ const UNC_PREFIX: &[u16] = &[SEP, SEP, QUERY, SEP, U, N, C, SEP]; - if path.starts_with(VERBATIM_PREFIX) || path.starts_with(NT_PREFIX) || path == &[0] { + if path.starts_with(VERBATIM_PREFIX) || path.starts_with(NT_PREFIX) || path == [0] { // Early return for paths that are already verbatim or empty. return Ok(path); } else if path.len() < LEGACY_MAX_PATH { From c15adf6557a43b51bae72252b49c89635dbee325 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Wed, 22 Nov 2023 00:02:04 +0000 Subject: [PATCH 61/66] manual_range_contains --- library/std/src/sys/windows/stdio.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/sys/windows/stdio.rs b/library/std/src/sys/windows/stdio.rs index 1765c221543a..819a48266d94 100644 --- a/library/std/src/sys/windows/stdio.rs +++ b/library/std/src/sys/windows/stdio.rs @@ -207,7 +207,7 @@ fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result= 0xDCEE && first_code_unit_remaining <= 0xDFFF { + if matches!(first_code_unit_remaining, 0xDCEE..=0xDFFF) { // low surrogate // We just hope this works, and give up otherwise let _ = write_u16s(handle, &utf16[written..written + 1]); @@ -332,7 +332,7 @@ fn read_u16s_fixup_surrogates( // and it is not 0, so we know that `buf[amount - 1]` have been // initialized. let last_char = unsafe { buf[amount - 1].assume_init() }; - if last_char >= 0xD800 && last_char <= 0xDBFF { + if matches!(last_char, 0xD800..=0xDBFF) { // high surrogate *surrogate = last_char; amount -= 1; From 852c0383930a80c646441104a89af59f949c9804 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Wed, 22 Nov 2023 00:09:33 +0000 Subject: [PATCH 62/66] cmp_null comparing with null is better expressed by the `.is_null()` method --- library/std/src/sys/windows/time.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/sys/windows/time.rs b/library/std/src/sys/windows/time.rs index bece48e799f8..09e78a29304f 100644 --- a/library/std/src/sys/windows/time.rs +++ b/library/std/src/sys/windows/time.rs @@ -1,7 +1,7 @@ use crate::cmp::Ordering; use crate::fmt; use crate::mem; -use crate::ptr::{null, null_mut}; +use crate::ptr::null; use crate::sys::c; use crate::sys_common::IntoInner; use crate::time::Duration; @@ -240,7 +240,7 @@ impl WaitableTimer { c::TIMER_ALL_ACCESS, ) }; - if handle != null_mut() { Ok(Self { handle }) } else { Err(()) } + if !handle.is_null() { Ok(Self { handle }) } else { Err(()) } } pub fn set(&self, duration: Duration) -> Result<(), ()> { // Convert the Duration to a format similar to FILETIME. From 6c8ebf174c3201ec6333e8bf2df291b88e338d35 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Wed, 22 Nov 2023 00:10:48 +0000 Subject: [PATCH 63/66] redundant_slicing --- library/std/src/sys/windows/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/mod.rs b/library/std/src/sys/windows/mod.rs index 14e34ffec4d2..9c83d6eb8bf6 100644 --- a/library/std/src/sys/windows/mod.rs +++ b/library/std/src/sys/windows/mod.rs @@ -150,7 +150,7 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { pub fn unrolled_find_u16s(needle: u16, haystack: &[u16]) -> Option { let ptr = haystack.as_ptr(); - let mut start = &haystack[..]; + let mut start = haystack; // For performance reasons unfold the loop eight times. while start.len() >= 8 { From b9fe367b9993c33a022411fd08e3da0081abacfd Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Wed, 22 Nov 2023 00:44:37 +0000 Subject: [PATCH 64/66] x fmt library/std --- library/std/src/sys/windows/process.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/library/std/src/sys/windows/process.rs b/library/std/src/sys/windows/process.rs index 8a442ca4acf7..51e16b9f13c9 100644 --- a/library/std/src/sys/windows/process.rs +++ b/library/std/src/sys/windows/process.rs @@ -917,9 +917,8 @@ fn make_proc_thread_attribute_list( ) }; - let mut proc_thread_attribute_list = ProcThreadAttributeList( - vec![MaybeUninit::uninit(); required_size].into_boxed_slice(), - ); + let mut proc_thread_attribute_list = + ProcThreadAttributeList(vec![MaybeUninit::uninit(); required_size].into_boxed_slice()); // Once we've allocated the necessary memory, it's safe to invoke // `InitializeProcThreadAttributeList` to properly initialize the list. From ec50f1c90b8da0c2ce567a5fbcf0d5202e5ed4fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 19 Nov 2023 16:34:22 +0000 Subject: [PATCH 65/66] When failing to import `core`, suggest `std` --- compiler/rustc_resolve/src/diagnostics.rs | 9 +++++++++ .../feature-gate-extern_absolute_paths.stderr | 12 ++++++++---- .../rfc-2632-const-trait-impl/issue-102156.stderr | 13 ++++++++----- .../simd/portable-intrinsics-arent-exposed.stderr | 7 ++++--- 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 93db6cfc4635..54c61708f945 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1858,6 +1858,15 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Applicability::MaybeIncorrect, )), ) + } else if ident.name == sym::core { + ( + format!("maybe a missing crate `{ident}`?"), + Some(( + vec![(ident.span, "std".to_string())], + "try using `std` instead of `core`".to_string(), + Applicability::MaybeIncorrect, + )), + ) } else if self.tcx.sess.is_rust_2015() { ( format!("maybe a missing crate `{ident}`?"), diff --git a/tests/ui/feature-gates/feature-gate-extern_absolute_paths.stderr b/tests/ui/feature-gates/feature-gate-extern_absolute_paths.stderr index 7de67da9b5d1..2fcad98be9f7 100644 --- a/tests/ui/feature-gates/feature-gate-extern_absolute_paths.stderr +++ b/tests/ui/feature-gates/feature-gate-extern_absolute_paths.stderr @@ -2,9 +2,10 @@ error[E0432]: unresolved import `core` --> $DIR/feature-gate-extern_absolute_paths.rs:1:5 | LL | use core::default; - | ^^^^ maybe a missing crate `core`? - | - = help: consider adding `extern crate core` to use the `core` crate + | ^^^^ + | | + | maybe a missing crate `core`? + | help: try using `std` instead of `core`: `std` error[E0433]: failed to resolve: maybe a missing crate `core`? --> $DIR/feature-gate-extern_absolute_paths.rs:4:19 @@ -12,7 +13,10 @@ error[E0433]: failed to resolve: maybe a missing crate `core`? LL | let _: u8 = ::core::default::Default(); | ^^^^ maybe a missing crate `core`? | - = help: consider adding `extern crate core` to use the `core` crate +help: try using `std` instead of `core` + | +LL | let _: u8 = ::std::default::Default(); + | ~~~ help: consider importing this module | LL + use std::default; diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.stderr b/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.stderr index e8ae7e4e36ce..c331236a4601 100644 --- a/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.stderr +++ b/tests/ui/rfcs/rfc-2632-const-trait-impl/issue-102156.stderr @@ -2,17 +2,20 @@ error[E0433]: failed to resolve: maybe a missing crate `core`? --> $DIR/issue-102156.rs:4:5 | LL | use core::convert::{From, TryFrom}; - | ^^^^ maybe a missing crate `core`? - | - = help: consider adding `extern crate core` to use the `core` crate + | ^^^^ + | | + | maybe a missing crate `core`? + | help: try using `std` instead of `core`: `std` error[E0433]: failed to resolve: maybe a missing crate `core`? --> $DIR/issue-102156.rs:4:5 | LL | use core::convert::{From, TryFrom}; - | ^^^^ maybe a missing crate `core`? + | ^^^^ + | | + | maybe a missing crate `core`? + | help: try using `std` instead of `core`: `std` | - = help: consider adding `extern crate core` to use the `core` crate = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: aborting due to 2 previous errors diff --git a/tests/ui/simd/portable-intrinsics-arent-exposed.stderr b/tests/ui/simd/portable-intrinsics-arent-exposed.stderr index f8b3e6d65afb..a6f27af428b5 100644 --- a/tests/ui/simd/portable-intrinsics-arent-exposed.stderr +++ b/tests/ui/simd/portable-intrinsics-arent-exposed.stderr @@ -2,9 +2,10 @@ error[E0433]: failed to resolve: maybe a missing crate `core`? --> $DIR/portable-intrinsics-arent-exposed.rs:4:5 | LL | use core::simd::intrinsics; - | ^^^^ maybe a missing crate `core`? - | - = help: consider adding `extern crate core` to use the `core` crate + | ^^^^ + | | + | maybe a missing crate `core`? + | help: try using `std` instead of `core`: `std` error[E0432]: unresolved import `std::simd::intrinsics` --> $DIR/portable-intrinsics-arent-exposed.rs:5:5 From 804afa4a94f4e9a502531c19c9a150eb1d33f4f6 Mon Sep 17 00:00:00 2001 From: The Miri Conjob Bot Date: Thu, 23 Nov 2023 04:55:03 +0000 Subject: [PATCH 66/66] Preparing for merge from rustc --- src/tools/miri/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index 00a41008d3b5..ee27d8ed9a86 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -0ff861096449f47956521b40e5e4e88caa7fe27c +360bafad68cfea2682cf016070e533c45a00150f