diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 994b67bee96..d8b2992cb93 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,10 +65,10 @@ jobs: - name: Checkout the standard-library backtrace submodule run: git submodule update --init --depth 1 library/backtrace - - name: Check compiler crates + - name: Check compiler crates and Clippy run: >- python3 x.py --ci false --set build.submodules=false --set rust.debug-assertions=true - --set rust.lto=off --warnings deny check compiler + --set rust.lto=off --warnings deny check compiler src/tools/clippy - name: Install Ninja for Linux distribution tests if: runner.os == 'Linux' diff --git a/compiler/rustc_ast_lowering/src/delegation/mod.rs b/compiler/rustc_ast_lowering/src/delegation/mod.rs index b2c0e1ffa81..de271a51bca 100644 --- a/compiler/rustc_ast_lowering/src/delegation/mod.rs +++ b/compiler/rustc_ast_lowering/src/delegation/mod.rs @@ -476,7 +476,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // FIXME(fn_delegation): add default `..` for all other fields. let initializer = hir::ExprKind::Struct( - self.arena.alloc(path), + self.arena.alloc(hir::StructQPath::new(path)), self.arena.alloc_slice(&[hir::ExprField { hir_id: self.next_id(), is_shorthand: false, diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index f4bfec24e3b..f3edab20ab2 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -508,7 +508,7 @@ impl<'hir> LoweringContext<'_, 'hir> { StructRest::NoneWithError(guar) => hir::StructTailExpr::NoneWithError(guar), }; hir::ExprKind::Struct( - self.arena.alloc(self.lower_qpath( + self.arena.alloc(hir::StructQPath::new(self.lower_qpath( e.id, &se.qself, &se.path, @@ -516,7 +516,7 @@ impl<'hir> LoweringContext<'_, 'hir> { AllowReturnTypeNotation::No, ImplTraitContext::Disallowed(ImplTraitPosition::Path), None, - )), + ))), self.arena.alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))), rest, ) @@ -1418,7 +1418,11 @@ impl<'hir> LoweringContext<'_, 'hir> { StructRest::Rest(span) => Some(self.lower_span(*span)), StructRest::None | StructRest::NoneWithError(_) => None, }; - let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted); + let struct_pat = hir::PatKind::Struct( + self.arena.alloc(hir::StructQPath::new(qpath)), + field_pats, + fields_omitted, + ); return self.pat_without_dbm(lhs.span, struct_pat); } // Tuples. @@ -1570,7 +1574,8 @@ impl<'hir> LoweringContext<'_, 'hir> { ); hir::ExprKind::Struct( - self.arena.alloc(self.make_lang_item_qpath(lang_item, span, None)), + self.arena + .alloc(hir::StructQPath::new(self.make_lang_item_qpath(lang_item, span, None))), fields, hir::StructTailExpr::None, ) @@ -2153,16 +2158,23 @@ impl<'hir> LoweringContext<'_, 'hir> { pub(super) fn expr_struct( &mut self, span: Span, - path: &'hir hir::QPath<'hir>, + path: hir::QPath<'hir>, fields: &'hir [hir::ExprField<'hir>], ) -> hir::Expr<'hir> { - self.expr(span, hir::ExprKind::Struct(path, fields, rustc_hir::StructTailExpr::None)) + self.expr( + span, + hir::ExprKind::Struct( + self.arena.alloc(hir::StructQPath::new(path)), + fields, + rustc_hir::StructTailExpr::None, + ), + ) } pub(super) fn expr_enum_variant( &mut self, span: Span, - path: &'hir hir::QPath<'hir>, + path: hir::QPath<'hir>, fields: &'hir [hir::Expr<'hir>], ) -> hir::Expr<'hir> { let fields = self.arena.alloc_from_iter(fields.into_iter().enumerate().map(|(i, f)| { @@ -2183,7 +2195,7 @@ impl<'hir> LoweringContext<'_, 'hir> { lang_item: LangItem, fields: &'hir [hir::Expr<'hir>], ) -> hir::Expr<'hir> { - let path = self.arena.alloc(self.make_lang_item_qpath(lang_item, span, None)); + let path = self.make_lang_item_qpath(lang_item, span, None); self.expr_enum_variant(span, path, fields) } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 18ee7acb655..8ca8675f760 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -3221,7 +3221,10 @@ impl<'hir> LoweringContext<'_, 'hir> { fields: &'hir [hir::PatField<'hir>], ) -> &'hir hir::Pat<'hir> { let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None); - self.pat(span, hir::PatKind::Struct(path, fields, None)) + self.pat( + span, + hir::PatKind::Struct(self.arena.alloc(hir::StructQPath::new(path)), fields, None), + ) } fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) { diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index df3d7b1a3c0..e5e1660bd6d 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -103,7 +103,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } })); break hir::PatKind::Struct( - qpath, + self.arena.alloc(hir::StructQPath::new(qpath)), fs, match etc { ast::PatFieldsRest::Rest(sp) => Some(self.lower_span(*sp)), diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index f4b2ceb8506..004e3b4ecb1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -1261,7 +1261,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { else { return; }; - let hir::QPath::Resolved(_, path) = struct_qpath else { return }; + let hir::QPath::Resolved(_, path) = struct_qpath.qpath else { return }; let hir::def::Res::Def(_, def_id) = path.res else { return }; let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return }; let ty::Adt(def, args) = expr_ty.kind() else { return }; @@ -2526,7 +2526,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { && let hir::ExprKind::Path(qpath) = path.kind && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext) && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind - && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome) + && self.tcx.qpath_is_lang_item(qpath.qpath, LangItem::OptionSome) && call.span.contains(self.issue_span) { // Find `` and the span for the whole `for` loop. diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 733db2b97c9..837f1ac6d6a 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1783,7 +1783,7 @@ pub enum PatKind<'hir> { /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`). /// The `Option` contains the span of a possible `..`. - Struct(QPath<'hir>, &'hir [PatField<'hir>], Option), + Struct(&'hir StructQPath<'hir>, &'hir [PatField<'hir>], Option), /// A tuple struct/variant pattern `Variant(x, y, .., z)`. /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position. @@ -2587,12 +2587,18 @@ impl Expr<'_> { ) => path1.res == path2.res, ( ExprKind::Struct( - &QPath::Resolved(None, &Path { res: Res::Def(_, path1_def_id), .. }), + &crate::StructQPath { + qpath: QPath::Resolved(None, &Path { res: Res::Def(_, path1_def_id), .. }), + .. + }, args1, StructTailExpr::None, ), ExprKind::Struct( - &QPath::Resolved(None, &Path { res: Res::Def(_, path2_def_id), .. }), + &crate::StructQPath { + qpath: QPath::Resolved(None, &Path { res: Res::Def(_, path2_def_id), .. }), + .. + }, args2, StructTailExpr::None, ), @@ -2619,7 +2625,11 @@ impl Expr<'_> { /// Checks if the specified expression is a built-in range literal. /// (See: `LoweringContext::lower_expr()`). pub fn is_range_literal(expr: &Expr<'_>) -> bool { - if let ExprKind::Struct(QPath::Resolved(None, path), _, StructTailExpr::None) = expr.kind + if let ExprKind::Struct( + crate::StructQPath { qpath: QPath::Resolved(None, path), .. }, + _, + StructTailExpr::None, + ) = expr.kind && let [.., segment] = path.segments && let sym::RangeFrom | sym::RangeFull @@ -2781,7 +2791,7 @@ pub enum ExprKind<'hir> { /// /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`, /// where `base` is the `Option`. - Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>), + Struct(&'hir StructQPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>), /// An array literal constructed from one repeated element. /// @@ -2862,6 +2872,39 @@ impl<'hir> QPath<'hir> { } } +/// The path of a struct literal or a struct pattern. +#[derive(Debug, Clone, Copy)] +pub struct StructQPath<'hir> { + pub qpath: QPath<'hir>, + pub(crate) joined_span: Span, +} + +impl<'hir> StructQPath<'hir> { + pub fn new(qpath: QPath<'hir>) -> Self { + // Joining different syntax contexts can consult the metavariable span map. + // Keep that lookup at its original demand, including after the map freezes. + let joined_span = match qpath { + QPath::TypeRelative(qself, segment) if qself.span.eq_ctxt(segment.ident.span) => { + qself.span.to(segment.ident.span) + } + _ => DUMMY_SP, + }; + Self { qpath, joined_span } + } + + pub fn span(&self) -> Span { + if self.joined_span == DUMMY_SP { self.qpath.span() } else { self.joined_span } + } +} + +impl<'hir> std::ops::Deref for StructQPath<'hir> { + type Target = QPath<'hir>; + + fn deref(&self) -> &QPath<'hir> { + &self.qpath + } +} + /// Hints at the original code for a let statement. #[derive(Copy, Clone, Debug, StableHash)] pub enum LocalSource { @@ -5388,14 +5431,15 @@ mod size_asserts { static_assert_size!(ItemKind<'_>, 64); static_assert_size!(LetStmt<'_>, 64); static_assert_size!(Param<'_>, 32); - static_assert_size!(Pat<'_>, 80); - static_assert_size!(PatKind<'_>, 56); + static_assert_size!(Pat<'_>, 72); + static_assert_size!(PatKind<'_>, 48); static_assert_size!(Path<'_>, 40); static_assert_size!(PathSegment<'_>, 48); static_assert_size!(QPath<'_>, 24); static_assert_size!(Res, 12); static_assert_size!(Stmt<'_>, 32); static_assert_size!(StmtKind<'_>, 16); + static_assert_size!(StructQPath<'_>, 32); static_assert_size!(TraitImplHeader<'_>, 48); static_assert_size!(TraitItem<'_>, 88); static_assert_size!(TraitItemKind<'_>, 48); diff --git a/compiler/rustc_hir/src/pat_util.rs b/compiler/rustc_hir/src/pat_util.rs index a47d9d5ca57..7f7bf1f0ede 100644 --- a/compiler/rustc_hir/src/pat_util.rs +++ b/compiler/rustc_hir/src/pat_util.rs @@ -110,7 +110,10 @@ impl hir::Pat<'_> { .. }) | PatKind::TupleStruct(hir::QPath::Resolved(_, path), ..) - | PatKind::Struct(hir::QPath::Resolved(_, path), ..) => { + | PatKind::Struct( + crate::StructQPath { qpath: hir::QPath::Resolved(_, path), .. }, + .., + ) => { if let Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), id) = path.res { diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index b0de52137ee..65b9573e1a9 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -1,6 +1,6 @@ use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher}; -use crate::hir::{AttributeMap, OwnerInfo, OwnerNodes}; +use crate::hir::{AttributeMap, OwnerInfo, OwnerNodes, QPath, StructQPath}; // The following implementations of StableHash for `ItemId`, `TraitItemId`, and // `ImplItemId` deserve special attention. Normally we do not hash `NodeId`s within @@ -39,3 +39,14 @@ impl<'tcx> StableHash for OwnerInfo<'tcx> { opt_hash.unwrap().stable_hash(hcx, hasher); } } + +impl StableHash for StructQPath<'_> { + fn stable_hash(&self, hcx: &mut Hcx, hasher: &mut StableHasher) { + self.qpath.stable_hash(hcx, hasher); + if let QPath::TypeRelative(..) = self.qpath { + // Two independently moving parents can change the joined geometry + // even when both source-relative operand fingerprints stay equal. + self.joined_span.stable_hash(hcx, hasher); + } + } +} diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index 76753711570..fa64c6f9a95 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -340,7 +340,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let ExprKind::Block(block, _) = then_expr.kind // Refutability checks occur on the MIR, so we approximate it here by checking // if we have an enum with a single variant or a struct in the pattern. - && let PatKind::TupleStruct(qpath, ..) | PatKind::Struct(qpath, ..) = pat.kind + && let PatKind::TupleStruct(qpath, ..) | PatKind::Struct(&hir::StructQPath { qpath, .. }, ..) = pat.kind && let hir::QPath::Resolved(_, path) = qpath { match path.res { diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 55eecef732a..88edaf6506e 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -1202,10 +1202,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { match expr.peel_drop_temps().kind { hir::ExprKind::Struct( - hir::QPath::Resolved( - None, - hir::Path { res: hir::def::Res::SelfTyAlias { alias_to, .. }, span, .. }, - ), + rustc_hir::StructQPath { + qpath: + hir::QPath::Resolved( + None, + hir::Path { + res: hir::def::Res::SelfTyAlias { alias_to, .. }, + span, + .. + }, + ), + .. + }, .., ) | hir::ExprKind::Call( diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 6202f2f11c9..90fb207af33 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1895,7 +1895,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, expr: &hir::Expr<'tcx>, expected: Expectation<'tcx>, - qpath: &'tcx QPath<'tcx>, + qpath: &'tcx hir::StructQPath<'tcx>, fields: &'tcx [hir::ExprField<'tcx>], base_expr: &'tcx hir::StructTailExpr<'tcx>, ) -> Ty<'tcx> { @@ -2440,7 +2440,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { mut err: Diag<'_>, ) { if is_range_literal(last_expr_field.expr) - && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind + && let ExprKind::Struct(&hir::StructQPath { qpath, .. }, [range_start, range_end], _) = + last_expr_field.expr.kind && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) && let variant_field = variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index d04aed3079b..ff2f7d89877 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -1058,7 +1058,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(crate) fn check_struct_path( &self, - qpath: &QPath<'tcx>, + qpath: &hir::StructQPath<'tcx>, hir_id: HirId, ) -> Result<(&'tcx ty::VariantDef, Ty<'tcx>), ErrorGuaranteed> { let path_span = qpath.span(); @@ -2384,8 +2384,8 @@ impl<'a, 'tcx> FnCallDiagCtxt<'a, 'tcx> { if let ty::Adt(adt, _) = ty.kind() && self.tcx().is_lang_item(adt.did(), LangItem::RangeFull) && is_range_literal(expr) - && let hir::ExprKind::Struct(&path, [], _) = expr.kind - && self.tcx().qpath_is_lang_item(path, LangItem::RangeFull) + && let hir::ExprKind::Struct(path, [], _) = expr.kind + && self.tcx().qpath_is_lang_item(path.qpath, LangItem::RangeFull) { // We have `Foo(a, .., c)`, where the user might be trying to use the "rest" syntax // from default field values, which is not supported on tuples. diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 57642a77026..d7748965ba9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1832,7 +1832,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return false; } match expr.kind { - ExprKind::Struct(&qpath, [start, end], _) + ExprKind::Struct(&hir::StructQPath { qpath, .. }, [start, end], _) if is_range_literal(expr) && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) => { @@ -1844,7 +1844,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); true } - ExprKind::Struct(&qpath, [arg], _) + ExprKind::Struct(&hir::StructQPath { qpath, .. }, [arg], _) if is_range_literal(expr) && let Some(qpath @ (LangItem::RangeFrom | LangItem::RangeTo)) = self.tcx.qpath_lang_item(qpath) => @@ -3794,7 +3794,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !hir::is_range_literal(expr) { return; } - let hir::ExprKind::Struct(&qpath, [start, end], _) = expr.kind else { + let hir::ExprKind::Struct(&hir::StructQPath { qpath, .. }, [start, end], _) = expr.kind + else { return; }; if !self.tcx.qpath_is_lang_item(qpath, LangItem::Range) { diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index f7279a64f13..b3976658ced 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -290,7 +290,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) | hir::Node::Pat(&hir::Pat { kind: - hir::PatKind::Struct(QPath::TypeRelative(rcvr, segment), ..) + hir::PatKind::Struct( + &rustc_hir::StructQPath { + qpath: QPath::TypeRelative(rcvr, segment), .. + }, + .., + ) | hir::PatKind::TupleStruct(QPath::TypeRelative(rcvr, segment), ..), span, .. @@ -2894,7 +2899,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { continue; } let lang_item = match parent_expr.kind { - ExprKind::Struct(qpath, _, _) => match tcx.qpath_lang_item(*qpath) { + ExprKind::Struct(qpath, _, _) => match tcx.qpath_lang_item(qpath.qpath) { Some( lang_item @ (LangItem::Range | LangItem::RangeCopy @@ -3791,7 +3796,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { let SelfSource::MethodCall(rcvr_expr) = source else { return }; let hir::ExprKind::Struct(qpath, fields, _) = rcvr_expr.kind else { return }; - let Some(lang_item) = self.tcx.qpath_lang_item(*qpath) else { + let Some(lang_item) = self.tcx.qpath_lang_item(qpath.qpath) else { return; }; let is_inclusive = match lang_item { diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index be439ec94ff..a96a92260fb 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -1565,7 +1565,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn resolve_pat_struct( &self, pat: &'tcx Pat<'tcx>, - qpath: &hir::QPath<'tcx>, + qpath: &hir::StructQPath<'tcx>, ) -> Result, ErrorGuaranteed> { // Resolve the path and check the definition for errors. let (variant, pat_ty) = self.check_struct_path(qpath, pat.hir_id)?; diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index b36326b86ac..8ae7ca87129 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -242,12 +242,16 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { }) | hir::Node::Pat(hir::Pat { kind: - hir::PatKind::TupleStruct(qpath, ..) | hir::PatKind::Struct(qpath, ..), + hir::PatKind::TupleStruct(qpath, ..) + | hir::PatKind::Struct(hir::StructQPath { qpath, .. }, ..), .. }) | hir::Node::Expr( hir::Expr { kind: hir::ExprKind::Path(qpath), .. } - | &hir::Expr { kind: hir::ExprKind::Struct(qpath, ..), .. }, + | &hir::Expr { + kind: hir::ExprKind::Struct(hir::StructQPath { qpath, .. }, ..), + .. + }, ) => { if let hir::QPath::TypeRelative(qpath_ty, ..) = qpath && qpath_ty.hir_id == ty.hir_id diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index d812dee1cc6..f3630513be7 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -1125,7 +1125,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { // impl is currently the `DefId` of `Output` in the trait definition // which makes this somewhat difficult and prevents us from just // using `self.path_inferred_arg_iter` here. - hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _) + hir::ExprKind::Struct(&rustc_hir::StructQPath { qpath: hir::QPath::Resolved(_self_ty, path), .. }, _, _) // FIXME(TaKO8Ki): Ideally we should support other kinds, // such as `TyAlias` or `AssocTy`. For that we have to map // back from the self type to the type alias though. That's difficult. diff --git a/src/tools/clippy/clippy_lints/src/manual_let_else.rs b/src/tools/clippy/clippy_lints/src/manual_let_else.rs index 87523cd0e8c..4856236567b 100644 --- a/src/tools/clippy/clippy_lints/src/manual_let_else.rs +++ b/src/tools/clippy/clippy_lints/src/manual_let_else.rs @@ -127,7 +127,7 @@ fn is_arms_disjointed(cx: &LateContext<'_>, arm1: &Arm<'_>, arm2: &Arm<'_>) -> b /// Returns `true` if the given pattern is a variant of an enum. pub fn is_enum_variant(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool { - let path = match pat.kind { + let path: (&QPath<'_>, _) = match pat.kind { PatKind::Struct(ref qpath, fields, _) if fields .iter() diff --git a/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs b/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs index 443e84f1638..3816b2f795d 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs @@ -59,7 +59,7 @@ pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) { // this is incorrect, as we should really check whether each variant is exhaustively // covered by the set of guards that cover it, but that's really hard to do. recurse_or_patterns(arm.pat, |pat| { - let path = match &peel_hir_pat_refs(pat).0.kind { + let path: &QPath<'_> = match &peel_hir_pat_refs(pat).0.kind { PatKind::Expr(PatExpr { hir_id, kind: PatExprKind::Path(path), diff --git a/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs b/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs index 4a0da636810..459657d4a56 100644 --- a/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs +++ b/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs @@ -1,5 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; -use rustc_hir::{Pat, PatKind, QPath}; +use clippy_utils::resolved_path; +use rustc_hir::{Pat, PatKind}; use rustc_lint::LateContext; use rustc_middle::ty; @@ -7,7 +8,8 @@ use super::REST_PAT_IN_FULLY_BOUND_STRUCTS; pub(crate) fn check(cx: &LateContext<'_>, pat: &Pat<'_>) { if !pat.span.from_expansion() - && let PatKind::Struct(QPath::Resolved(_, path), fields, Some(dotdot)) = pat.kind + && let PatKind::Struct(ref qpath, fields, Some(dotdot)) = pat.kind + && let Some(path) = resolved_path(qpath) && let Some(def_id) = path.res.opt_def_id() && let ty = cx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip() && let ty::Adt(def, _) = ty.kind() diff --git a/src/tools/clippy/clippy_lints/src/methods/string_from_utf8_as_bytes.rs b/src/tools/clippy/clippy_lints/src/methods/string_from_utf8_as_bytes.rs index 97506d795cd..8e31cfe3153 100644 --- a/src/tools/clippy/clippy_lints/src/methods/string_from_utf8_as_bytes.rs +++ b/src/tools/clippy/clippy_lints/src/methods/string_from_utf8_as_bytes.rs @@ -6,10 +6,11 @@ use clippy_utils::{method_calls, sym}; use rustc_ast::BorrowKind; use rustc_errors::Applicability; use rustc_hir::attrs::lang_items::LangItem; -use rustc_hir::{Expr, ExprKind}; +use rustc_hir::{Expr, ExprKind, QPath}; use rustc_lint::LateContext; pub(super) fn check_call(cx: &LateContext<'_>, expr: &Expr<'_>, fun: &Expr<'_>, args: &[Expr<'_>]) { + let is_range = |qpath: &QPath<'_>| cx.tcx.qpath_is_lang_item(*qpath, LangItem::Range); // Find `std::str::converts::from_utf8` or `std::primitive::str::from_utf8` if let [bytes_arg] = args && let Some(sym::str_from_utf8 | sym::str_inherent_from_utf8) = @@ -24,8 +25,8 @@ pub(super) fn check_call(cx: &LateContext<'_>, expr: &Expr<'_>, fun: &Expr<'_>, && expressions[0].1.is_empty() // Check for slicer - && let ExprKind::Struct(&qpath, _, _) = right.kind - && cx.tcx.qpath_is_lang_item(qpath, LangItem::Range) + && let ExprKind::Struct(qpath, _, _) = right.kind + && is_range(qpath) { let mut applicability = Applicability::MachineApplicable; let string_expression = &expressions[0].0; diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index ddc61b24498..c837fb95c7f 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then}; use clippy_utils::sugg::Sugg; -use clippy_utils::{fulfill_or_allowed, in_automatically_derived}; +use clippy_utils::{fulfill_or_allowed, in_automatically_derived, resolved_path}; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::def_id::LocalDefId; @@ -193,8 +193,9 @@ fn check_used_underscore<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { }, ExprKind::MethodCall(path, ..) => (path.ident, Id::TyRel), ExprKind::Struct(path, ..) => match path { - QPath::Resolved(_, path) - if let Some(id) = Id::from_res(path.res) + qpath + if let Some(path) = resolved_path(qpath) + && let Some(id) = Id::from_res(path.res) && let [.., seg] = path.segments => { (seg.ident, id) diff --git a/src/tools/clippy/clippy_lints/src/unneeded_struct_pattern.rs b/src/tools/clippy/clippy_lints/src/unneeded_struct_pattern.rs index 687fbdac2e2..82c4a9502ca 100644 --- a/src/tools/clippy/clippy_lints/src/unneeded_struct_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/unneeded_struct_pattern.rs @@ -1,8 +1,8 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::is_from_proc_macro; +use clippy_utils::{is_from_proc_macro, resolved_path}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::{Pat, PatKind, QPath}; +use rustc_hir::{Pat, PatKind}; use rustc_lint::{LateContext, LateLintPass, declare_lint_pass}; declare_clippy_lint! { @@ -42,8 +42,8 @@ declare_lint_pass!(UnneededStructPattern => [UNNEEDED_STRUCT_PATTERN]); impl LateLintPass<'_> for UnneededStructPattern { fn check_pat(&mut self, cx: &LateContext<'_>, pat: &Pat<'_>) { if !pat.span.from_expansion() - && let PatKind::Struct(path, [], _) = &pat.kind - && let QPath::Resolved(_, path) = path + && let PatKind::Struct(ref qpath, [], _) = pat.kind + && let Some(path) = resolved_path(qpath) && let Res::Def(DefKind::Variant, did) = path.res { let enum_did = cx.tcx.parent(did); @@ -55,7 +55,7 @@ impl LateLintPass<'_> for UnneededStructPattern { return; } - if is_from_proc_macro(cx, *path) { + if is_from_proc_macro(cx, path) { return; } diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 7b4250c6078..03e7ba10c05 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -1,8 +1,8 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::is_from_proc_macro; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::ty::{same_type_modulo_regions, ty_from_hir_ty}; +use clippy_utils::{is_from_proc_macro, resolved_path}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::{CtorOf, DefKind, Res}; @@ -235,7 +235,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { && self.msrv.meets(cx, msrvs::TYPE_ALIAS_ENUM_VARIANTS) { match expr.kind { - ExprKind::Struct(QPath::Resolved(_, path), ..) => check_path(cx, path), + ExprKind::Struct(qpath, ..) if let Some(path) = resolved_path(qpath) => check_path(cx, path), ExprKind::Call(fun, _) => { if let ExprKind::Path(QPath::Resolved(_, path)) = fun.kind { check_path(cx, path); @@ -250,10 +250,15 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { fn check_pat(&mut self, cx: &LateContext<'_>, pat: &Pat<'_>) { if !pat.span.from_expansion() && let Some(&StackItem::Check { impl_id, .. }) = self.stack.last() - // get the path from the pattern - && let PatKind::Expr(&PatExpr { kind: PatExprKind::Path(QPath::Resolved(_, path)), .. }) - | PatKind::TupleStruct(QPath::Resolved(_, path), _, _) - | PatKind::Struct(QPath::Resolved(_, path), _, _) = pat.kind + && let Some(path) = match &pat.kind { + PatKind::Expr(PatExpr { + kind: PatExprKind::Path(QPath::Resolved(_, path)), + .. + }) + | PatKind::TupleStruct(QPath::Resolved(_, path), _, _) => Some(*path), + PatKind::Struct(qpath, _, _) => resolved_path(qpath), + _ => None, + } && cx.typeck_results().pat_ty(pat) == cx.tcx.type_of(impl_id).instantiate_identity().skip_norm_wip() && self.msrv.meets(cx, msrvs::TYPE_ALIAS_ENUM_VARIANTS) { diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index a32a641c34e..7047ad74758 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -686,7 +686,8 @@ impl<'a, 'tcx> PrintVisitor<'a, 'tcx> { bind!(self, container, fields); kind!("OffsetOf({container}, {fields})"); }, - ExprKind::Struct(qpath, fields, base) => { + ExprKind::Struct(path, fields, base) => { + let qpath: &QPath<'_> = path; bind!(self, qpath, fields); let base = OptionPat::new(match base { StructTailExpr::Base(base) => Some(self.bind("base", base)), @@ -778,7 +779,8 @@ impl<'a, 'tcx> PrintVisitor<'a, 'tcx> { self.ident(name); sub.if_some(|p| self.pat(p)); }, - PatKind::Struct(ref qpath, fields, etc) => { + PatKind::Struct(ref path, fields, etc) => { + let qpath: &QPath<'_> = path; let ignore = etc.is_some(); bind!(self, qpath, fields); kind!("Struct(ref {qpath}, {fields}, {ignore})"); diff --git a/src/tools/clippy/clippy_utils/src/higher.rs b/src/tools/clippy/clippy_utils/src/higher.rs index 8d37f8df3f0..cc8c1fd499e 100644 --- a/src/tools/clippy/clippy_utils/src/higher.rs +++ b/src/tools/clippy/clippy_utils/src/higher.rs @@ -219,14 +219,15 @@ impl<'a> Range<'a> { /// Higher a `hir` range to something similar to `ast::ExprKind::Range`. pub fn hir(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option> { let span = expr.range_span()?; + let lang_item = |path: &QPath<'_>| cx.tcx.qpath_lang_item(*path); let (ty, start, end) = match expr.kind { ExprKind::Call(path, [arg1, arg2]) if let ExprKind::Path(qpath) = path.kind - && cx.tcx.qpath_is_lang_item(qpath, LangItem::RangeInclusiveNew) => + && lang_item(&qpath) == Some(LangItem::RangeInclusiveNew) => { (RangeTy::OpsInclusive, Some(arg1), Some(arg2)) }, - ExprKind::Struct(&qpath, fields, StructTailExpr::None) => match (cx.tcx.qpath_lang_item(qpath)?, fields) { + ExprKind::Struct(qpath, fields, StructTailExpr::None) => match (lang_item(qpath)?, fields) { (LangItem::RangeFull, []) => (RangeTy::OpsFull, None, None), (LangItem::RangeFrom, [start]) if start.ident.name == sym::start => { (RangeTy::OpsFrom, Some(start.expr), None) diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 81d8ab4fb3e..b68f2cde6bc 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -406,6 +406,14 @@ pub fn is_def_id_trait_method(cx: &LateContext<'_>, def_id: LocalDefId) -> bool } } +/// Returns the resolved path, if name resolution did not defer it to type checking. +pub fn resolved_path<'tcx>(qpath: &QPath<'tcx>) -> Option<&'tcx Path<'tcx>> { + match *qpath { + QPath::Resolved(_, path) => Some(path), + QPath::TypeRelative(..) => None, + } +} + pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> { match *path { QPath::Resolved(_, path) => path.segments.last().expect("A path must have at least one segment"), diff --git a/tests/run-make/hir-struct-path-span/client.rs b/tests/run-make/hir-struct-path-span/client.rs new file mode 100644 index 00000000000..fa010f378f6 --- /dev/null +++ b/tests/run-make/hir-struct-path-span/client.rs @@ -0,0 +1,38 @@ +#![feature(more_qualified_paths)] +extern crate qpath_macros; +extern crate qpath_support; + +pub enum Value { + #[deprecated(note = "qualified variant geometry")] + Node { + value: u8, + }, + Other, +} +impl Value { + pub fn ordinary_struct() -> Self { + Self::Node { value: 1 } + } + pub fn qualified_struct() -> Self { + ::Node { value: 2 } + } + pub fn external_parts() -> Self { + qpath_support::mixed_node!(Self, 3) + } + pub fn supplied_parts() -> Self { + qpath_support::two_inputs!(Self, Node, 5) + } + pub fn procedural_parts() -> Self { + qpath_macros::make_mixed!(Self) + } + pub fn matched_struct(self) -> u8 { + match self { + Self::Node { value } => value, + _ => 0, + } + } + pub fn extra_check() -> Self { + Self::Node { value: 8 } + } +} +include!("included.rs"); diff --git a/tests/run-make/hir-struct-path-span/included.rs.in b/tests/run-make/hir-struct-path-span/included.rs.in new file mode 100644 index 00000000000..9bd210c4f68 --- /dev/null +++ b/tests/run-make/hir-struct-path-span/included.rs.in @@ -0,0 +1,5 @@ + +impl Value { + pub fn included_relative() -> Self { Self::Node { value: 6 } } + pub fn included_external() -> Self { qpath_support::mixed_node!(Self, 7) } +} diff --git a/tests/run-make/hir-struct-path-span/qpath_macros.rs b/tests/run-make/hir-struct-path-span/qpath_macros.rs new file mode 100644 index 00000000000..1ce4398d966 --- /dev/null +++ b/tests/run-make/hir-struct-path-span/qpath_macros.rs @@ -0,0 +1,18 @@ +extern crate proc_macro; +use proc_macro::{Ident, Span, TokenStream, TokenTree}; + +#[proc_macro] +pub fn make_mixed(input: TokenStream) -> TokenStream { + let ty = input.into_iter().next().unwrap(); + let tokens: TokenStream = "::Node { value: 4 }".parse().unwrap(); + tokens + .into_iter() + .map(|t| match t { + TokenTree::Ident(ref ident) if ident.to_string() == "TypeHole" => ty.clone(), + TokenTree::Ident(ref ident) if ident.to_string() == "Node" => { + TokenTree::Ident(Ident::new("Node", Span::mixed_site())) + } + other => other, + }) + .collect() +} diff --git a/tests/run-make/hir-struct-path-span/qpath_support.rs b/tests/run-make/hir-struct-path-span/qpath_support.rs new file mode 100644 index 00000000000..7f8fb78023d --- /dev/null +++ b/tests/run-make/hir-struct-path-span/qpath_support.rs @@ -0,0 +1,14 @@ +#![crate_type = "rlib"] + +#[macro_export] +macro_rules! mixed_node { + ($ty:ty, $v:expr) => { + <$ty>::Node { value: $v } + }; +} +#[macro_export] +macro_rules! two_inputs { + ($ty:ty, $name:ident, $v:expr) => { + <$ty>::$name { value: $v } + }; +} diff --git a/tests/run-make/hir-struct-path-span/rmake.rs b/tests/run-make/hir-struct-path-span/rmake.rs new file mode 100644 index 00000000000..957d4c9dace --- /dev/null +++ b/tests/run-make/hir-struct-path-span/rmake.rs @@ -0,0 +1,49 @@ +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::rustc; + +fn build(cache: &str, error: bool) -> String { + let mut cmd = rustc(); + cmd.input("input.rs") + .arg("--edition=2024") + .arg("--error-format=json") + .arg("--emit=metadata=libqpath_sample.rmeta") + .arg("--crate-name=qpath_sample") + .arg("--crate-type=rlib") + .arg("-Cmetadata=qpath_geometry") + .arg(format!("-Cincremental={cache}")) + .arg("-Zincremental-verify-ich") + .arg("-L.") + .arg("--extern=qpath_macros") + .arg("--extern=qpath_support"); + let output = if error { cmd.run_fail() } else { cmd.run() }; + output.stderr_utf8() +} + +fn main() { + rustc().input("qpath_support.rs").arg("--edition=2024").arg("--crate-type=rlib").run(); + rustc().input("qpath_macros.rs").arg("--edition=2024").arg("--crate-type=proc-macro").run(); + + let original = fs::read_to_string("client.rs").unwrap(); + let included = fs::read_to_string("included.rs.in").unwrap(); + fs::write("input.rs", &original).unwrap(); + fs::write("included.rs", &included).unwrap(); + build("incremental", false); + + let shifted = format!("\n\n\n\n\n{included}"); + fs::write("included.rs", shifted).unwrap(); + let changed = build("incremental", false); + let warm_metadata = fs::read("libqpath_sample.rmeta").unwrap(); + assert_eq!(changed, build("empty-success", false)); + assert_eq!(warm_metadata, fs::read("libqpath_sample.rmeta").unwrap()); + assert!(changed.contains("qualified variant geometry")); + + let erroneous = original.replace("Self::Node { value: 8 }", "Self::Node {}"); + assert_ne!(erroneous, original); + fs::write("input.rs", erroneous).unwrap(); + let warm_error = build("incremental", true); + assert_eq!(warm_error, build("empty-error", true)); + assert!(warm_error.contains("E0063")); +}