From cc6cbaad4b0b62796ccc27e50cd80a4a85b70add Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 23 Dec 2023 00:37:35 +0100 Subject: [PATCH 01/12] Add missing CFI sanitizer cfgs feature gate --- compiler/rustc_feature/src/builtin_attrs.rs | 2 ++ compiler/rustc_feature/src/unstable.rs | 2 ++ compiler/rustc_span/src/symbol.rs | 1 + .../feature-gate-cfg-sanitizer_cfi.rs | 9 ++++++++ .../feature-gate-cfg-sanitizer_cfi.stderr | 21 +++++++++++++++++++ ...itizer-cfi-generalize-pointers-attr-cfg.rs | 2 ++ ...nitizer-cfi-normalize-integers-attr-cfg.rs | 2 ++ 7 files changed, 39 insertions(+) create mode 100644 tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.rs create mode 100644 tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.stderr diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 5523543cd4fb9..4442b67df6e28 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -36,6 +36,8 @@ const GATED_CFGS: &[GatedCfg] = &[ (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)), (sym::version, sym::cfg_version, cfg_fn!(cfg_version)), (sym::relocation_model, sym::cfg_relocation_model, cfg_fn!(cfg_relocation_model)), + (sym::sanitizer_cfi_generalize_pointers, sym::cfg_sanitizer_cfi, cfg_fn!(cfg_sanitizer_cfi)), + (sym::sanitizer_cfi_normalize_integers, sym::cfg_sanitizer_cfi, cfg_fn!(cfg_sanitizer_cfi)), ]; /// Find a gated cfg determined by the `pred`icate which is given the cfg's name. diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index bbf5e03117572..9ef59d4be14e3 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -369,6 +369,8 @@ declare_features! ( (unstable, cfg_relocation_model, "1.73.0", Some(114929)), /// Allows the use of `#[cfg(sanitize = "option")]`; set when -Zsanitizer is used. (unstable, cfg_sanitize, "1.41.0", Some(39699)), + /// Allows `cfg(sanitizer_cfi_generalize_pointers)` and `cfg(sanitizer_cfi_normalize_integers)`. + (unstable, cfg_sanitizer_cfi, "CURRENT_RUSTC_VERSION", Some(89653)), /// Allows `cfg(target_abi = "...")`. (unstable, cfg_target_abi, "1.55.0", Some(80970)), /// Allows `cfg(target(abi = "..."))`. diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 0333b5f04c3bc..8382298b16cbc 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -496,6 +496,7 @@ symbols! { cfg_panic, cfg_relocation_model, cfg_sanitize, + cfg_sanitizer_cfi, cfg_target_abi, cfg_target_compact, cfg_target_feature, diff --git a/tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.rs b/tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.rs new file mode 100644 index 0000000000000..76d96de750a62 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.rs @@ -0,0 +1,9 @@ +#[cfg(sanitizer_cfi_generalize_pointers)] +//~^ `cfg(sanitizer_cfi_generalize_pointers)` is experimental +fn foo() {} + +#[cfg(sanitizer_cfi_normalize_integers)] +//~^ `cfg(sanitizer_cfi_normalize_integers)` is experimental +fn bar() {} + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.stderr b/tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.stderr new file mode 100644 index 0000000000000..8c2a8411c7b4b --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-cfg-sanitizer_cfi.stderr @@ -0,0 +1,21 @@ +error[E0658]: `cfg(sanitizer_cfi_generalize_pointers)` is experimental and subject to change + --> $DIR/feature-gate-cfg-sanitizer_cfi.rs:1:7 + | +LL | #[cfg(sanitizer_cfi_generalize_pointers)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #89653 for more information + = help: add `#![feature(cfg_sanitizer_cfi)]` to the crate attributes to enable + +error[E0658]: `cfg(sanitizer_cfi_normalize_integers)` is experimental and subject to change + --> $DIR/feature-gate-cfg-sanitizer_cfi.rs:5:7 + | +LL | #[cfg(sanitizer_cfi_normalize_integers)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #89653 for more information + = help: add `#![feature(cfg_sanitizer_cfi)]` to the crate attributes to enable + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/sanitize/sanitizer-cfi-generalize-pointers-attr-cfg.rs b/tests/ui/sanitize/sanitizer-cfi-generalize-pointers-attr-cfg.rs index 3a0fc143da6fb..5b8de5c219e13 100644 --- a/tests/ui/sanitize/sanitizer-cfi-generalize-pointers-attr-cfg.rs +++ b/tests/ui/sanitize/sanitizer-cfi-generalize-pointers-attr-cfg.rs @@ -5,5 +5,7 @@ // check-pass // compile-flags: -Clto -Cno-prepopulate-passes -Ctarget-feature=-crt-static -Zsanitizer=cfi -Zsanitizer-cfi-generalize-pointers +#![feature(cfg_sanitizer_cfi)] + #[cfg(sanitizer_cfi_generalize_pointers)] fn main() {} diff --git a/tests/ui/sanitize/sanitizer-cfi-normalize-integers-attr-cfg.rs b/tests/ui/sanitize/sanitizer-cfi-normalize-integers-attr-cfg.rs index dafc20162abc1..4972ccf31678e 100644 --- a/tests/ui/sanitize/sanitizer-cfi-normalize-integers-attr-cfg.rs +++ b/tests/ui/sanitize/sanitizer-cfi-normalize-integers-attr-cfg.rs @@ -5,5 +5,7 @@ // check-pass // compile-flags: -Clto -Cno-prepopulate-passes -Ctarget-feature=-crt-static -Zsanitizer=cfi -Zsanitizer-cfi-normalize-integers +#![feature(cfg_sanitizer_cfi)] + #[cfg(sanitizer_cfi_normalize_integers)] fn main() {} From c88b021782aff93102c8d449829a30210d67b2ab Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 23 Dec 2023 00:48:14 +0100 Subject: [PATCH 02/12] Adjust the std library for sanitizer_cfi cfgs changes --- library/std/src/lib.rs | 1 + library/std/src/sys/unix/thread_local_dtor.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 76081833e05eb..1f63c76f35f33 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -265,6 +265,7 @@ // // Language features: // tidy-alphabetical-start +#![cfg_attr(not(bootstrap), feature(cfg_sanitizer_cfi))] #![feature(alloc_error_handler)] #![feature(allocator_internals)] #![feature(allow_internal_unsafe)] diff --git a/library/std/src/sys/unix/thread_local_dtor.rs b/library/std/src/sys/unix/thread_local_dtor.rs index ac85531c372ea..58f7ab84101ae 100644 --- a/library/std/src/sys/unix/thread_local_dtor.rs +++ b/library/std/src/sys/unix/thread_local_dtor.rs @@ -11,7 +11,7 @@ // Note, however, that we run on lots older linuxes, as well as cross // compiling from a newer linux to an older linux, so we also have a // fallback implementation to use as well. -#[allow(unexpected_cfgs)] +#[cfg_attr(bootstrap, allow(unexpected_cfgs))] #[cfg(any( target_os = "linux", target_os = "android", From 8bb74c0187482f92cd1347d670d5680a457c37a9 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 25 Dec 2023 13:14:12 +0000 Subject: [PATCH 03/12] Pass DeadItem and lint as consistent group in dead-code. --- compiler/rustc_passes/src/dead.rs | 107 ++++++++---------- compiler/rustc_passes/src/lib.rs | 1 + .../multiple-dead-codes-in-the-same-struct.rs | 4 + 3 files changed, 50 insertions(+), 62 deletions(-) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index d270794978b27..22aac1e775e6f 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -4,7 +4,6 @@ // is dead. use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; -use itertools::Itertools; use rustc_data_structures::unord::UnordSet; use rustc_errors::MultiSpan; use rustc_hir as hir; @@ -16,7 +15,8 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::privacy::Level; use rustc_middle::query::Providers; use rustc_middle::ty::{self, TyCtxt}; -use rustc_session::lint; +use rustc_session::lint::builtin::{DEAD_CODE, UNUSED_TUPLE_STRUCT_FIELDS}; +use rustc_session::lint::{self, Lint, LintId}; use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::FieldIdx; use std::mem; @@ -762,7 +762,7 @@ struct DeadVisitor<'tcx> { } enum ShouldWarnAboutField { - Yes(bool), // positional? + Yes, No, } @@ -784,7 +784,12 @@ impl<'tcx> DeadVisitor<'tcx> { { return ShouldWarnAboutField::No; } - ShouldWarnAboutField::Yes(is_positional) + ShouldWarnAboutField::Yes + } + + fn def_lint_level(&self, lint: &'static Lint, id: LocalDefId) -> lint::Level { + let hir_id = self.tcx.local_def_id_to_hir_id(id); + self.tcx.lint_level_at_node(lint, hir_id).0 } // # Panics @@ -795,38 +800,33 @@ impl<'tcx> DeadVisitor<'tcx> { // since those methods group by lint level before calling this method. fn lint_at_single_level( &self, - dead_codes: &[LocalDefId], + dead_codes: &[&DeadItem], participle: &str, parent_item: Option, - is_positional: bool, + lint: &'static Lint, ) { - let Some(&first_id) = dead_codes.first() else { + let Some(&first_item) = dead_codes.first() else { return; }; let tcx = self.tcx; - let first_hir_id = tcx.local_def_id_to_hir_id(first_id); - let first_lint_level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, first_hir_id).0; - assert!(dead_codes.iter().skip(1).all(|id| { - let hir_id = tcx.local_def_id_to_hir_id(*id); - let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0; - level == first_lint_level - })); + let first_lint_level = first_item.level; + assert!(dead_codes.iter().skip(1).all(|item| item.level == first_lint_level)); - let names: Vec<_> = - dead_codes.iter().map(|&def_id| tcx.item_name(def_id.to_def_id())).collect(); + let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect(); let spans: Vec<_> = dead_codes .iter() - .map(|&def_id| match tcx.def_ident_span(def_id) { - Some(s) => s.with_ctxt(tcx.def_span(def_id).ctxt()), - None => tcx.def_span(def_id), + .map(|item| match tcx.def_ident_span(item.def_id) { + Some(s) => s.with_ctxt(tcx.def_span(item.def_id).ctxt()), + None => tcx.def_span(item.def_id), }) .collect(); - let descr = tcx.def_descr(first_id.to_def_id()); + let descr = tcx.def_descr(first_item.def_id.to_def_id()); // `impl` blocks are "batched" and (unlike other batching) might // contain different kinds of associated items. - let descr = if dead_codes.iter().any(|did| tcx.def_descr(did.to_def_id()) != descr) { + let descr = if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) + { "associated item" } else { descr @@ -835,12 +835,6 @@ impl<'tcx> DeadVisitor<'tcx> { let multiple = num > 6; let name_list = names.into(); - let lint = if is_positional { - lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS - } else { - lint::builtin::DEAD_CODE - }; - let parent_info = if let Some(parent_item) = parent_item { let parent_descr = tcx.def_descr(parent_item.to_def_id()); let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) { @@ -853,7 +847,7 @@ impl<'tcx> DeadVisitor<'tcx> { None }; - let encl_def_id = parent_item.unwrap_or(first_id); + let encl_def_id = parent_item.unwrap_or(first_item.def_id); let ignored_derived_impls = if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) { let trait_list = ign_traits @@ -870,7 +864,7 @@ impl<'tcx> DeadVisitor<'tcx> { None }; - let diag = if is_positional { + let diag = if LintId::of(lint) == LintId::of(UNUSED_TUPLE_STRUCT_FIELDS) { MultipleDeadCodes::UnusedTupleStructFields { multiple, num, @@ -893,7 +887,8 @@ impl<'tcx> DeadVisitor<'tcx> { } }; - self.tcx.emit_spanned_lint(lint, first_hir_id, MultiSpan::from_spans(spans), diag); + let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id); + self.tcx.emit_spanned_lint(lint, hir_id, MultiSpan::from_spans(spans), diag); } fn warn_multiple( @@ -901,7 +896,7 @@ impl<'tcx> DeadVisitor<'tcx> { def_id: LocalDefId, participle: &str, dead_codes: Vec, - is_positional: bool, + lint: &'static Lint, ) { let mut dead_codes = dead_codes .iter() @@ -911,18 +906,18 @@ impl<'tcx> DeadVisitor<'tcx> { return; } dead_codes.sort_by_key(|v| v.level); - for (_, group) in &dead_codes.into_iter().group_by(|v| v.level) { - self.lint_at_single_level( - &group.map(|v| v.def_id).collect::>(), - participle, - Some(def_id), - is_positional, - ); + for group in dead_codes[..].group_by(|a, b| a.level == b.level) { + self.lint_at_single_level(&group, participle, Some(def_id), lint); } } fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) { - self.lint_at_single_level(&[id], participle, None, false); + let item = DeadItem { + def_id: id, + name: self.tcx.item_name(id.to_def_id()), + level: self.def_lint_level(DEAD_CODE, id), + }; + self.lint_at_single_level(&[&item], participle, None, DEAD_CODE); } fn check_definition(&mut self, def_id: LocalDefId) { @@ -969,13 +964,12 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) { let def_id = item.id.owner_id.def_id; if !visitor.is_live_code(def_id) { let name = tcx.item_name(def_id.to_def_id()); - let hir_id = tcx.local_def_id_to_hir_id(def_id); - let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0; + let level = visitor.def_lint_level(DEAD_CODE, def_id); dead_items.push(DeadItem { def_id, name, level }) } } - visitor.warn_multiple(item.owner_id.def_id, "used", dead_items, false); + visitor.warn_multiple(item.owner_id.def_id, "used", dead_items, DEAD_CODE); } if !live_symbols.contains(&item.owner_id.def_id) { @@ -997,43 +991,32 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) { let def_id = variant.def_id.expect_local(); if !live_symbols.contains(&def_id) { // Record to group diagnostics. - let hir_id = tcx.local_def_id_to_hir_id(def_id); - let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0; + let level = visitor.def_lint_level(DEAD_CODE, def_id); dead_variants.push(DeadItem { def_id, name: variant.name, level }); continue; } - let mut is_positional = false; + let is_positional = variant.fields.raw.first().map_or(false, |field| { + field.name.as_str().starts_with(|c: char| c.is_ascii_digit()) + }); + let lint = if is_positional { UNUSED_TUPLE_STRUCT_FIELDS } else { DEAD_CODE }; let dead_fields = variant .fields .iter() .filter_map(|field| { let def_id = field.did.expect_local(); - let hir_id = tcx.local_def_id_to_hir_id(def_id); - if let ShouldWarnAboutField::Yes(is_pos) = - visitor.should_warn_about_field(field) - { - let level = tcx - .lint_level_at_node( - if is_pos { - is_positional = true; - lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS - } else { - lint::builtin::DEAD_CODE - }, - hir_id, - ) - .0; + if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) { + let level = visitor.def_lint_level(lint, def_id); Some(DeadItem { def_id, name: field.name, level }) } else { None } }) .collect(); - visitor.warn_multiple(def_id, "read", dead_fields, is_positional); + visitor.warn_multiple(def_id, "read", dead_fields, lint); } - visitor.warn_multiple(item.owner_id.def_id, "constructed", dead_variants, false); + visitor.warn_multiple(item.owner_id.def_id, "constructed", dead_variants, DEAD_CODE); } } diff --git a/compiler/rustc_passes/src/lib.rs b/compiler/rustc_passes/src/lib.rs index c969867e871a6..bb33a4feb0556 100644 --- a/compiler/rustc_passes/src/lib.rs +++ b/compiler/rustc_passes/src/lib.rs @@ -12,6 +12,7 @@ #![feature(let_chains)] #![feature(map_try_insert)] #![feature(min_specialization)] +#![feature(slice_group_by)] #![feature(try_blocks)] #![recursion_limit = "256"] #![deny(rustc::untranslatable_diagnostic)] diff --git a/tests/ui/lint/dead-code/multiple-dead-codes-in-the-same-struct.rs b/tests/ui/lint/dead-code/multiple-dead-codes-in-the-same-struct.rs index 2003e1e293a58..a478153b3f480 100644 --- a/tests/ui/lint/dead-code/multiple-dead-codes-in-the-same-struct.rs +++ b/tests/ui/lint/dead-code/multiple-dead-codes-in-the-same-struct.rs @@ -15,6 +15,10 @@ struct Bar { _h: usize, } +// Issue 119267: this should not ICE. +#[derive(Debug)] +struct Foo(usize, #[allow(unused)] usize); + fn main() { Bar { a: 1, From eebb2abe0bd7d434ac3739e847c7b7452545d1c5 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 26 Dec 2023 01:59:18 +0000 Subject: [PATCH 04/12] Yeet some lifetimes --- compiler/rustc_pattern_analysis/src/lib.rs | 2 +- compiler/rustc_pattern_analysis/src/lints.rs | 20 +++---- compiler/rustc_pattern_analysis/src/pat.rs | 2 +- .../rustc_pattern_analysis/src/usefulness.rs | 56 +++++++++---------- 4 files changed, 40 insertions(+), 40 deletions(-) diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs index a1c9b15766676..e01b571ede101 100644 --- a/compiler/rustc_pattern_analysis/src/lib.rs +++ b/compiler/rustc_pattern_analysis/src/lib.rs @@ -91,7 +91,7 @@ pub struct MatchCtxt<'a, 'p, Cx: TypeCx> { /// The context for type information. pub tycx: &'a Cx, /// An arena to store the wildcards we produce during analysis. - pub wildcard_arena: &'a TypedArena>, + pub wildcard_arena: &'p TypedArena>, } /// The arm of a match expression. diff --git a/compiler/rustc_pattern_analysis/src/lints.rs b/compiler/rustc_pattern_analysis/src/lints.rs index 2be6e8e3db346..e8b714204a3cf 100644 --- a/compiler/rustc_pattern_analysis/src/lints.rs +++ b/compiler/rustc_pattern_analysis/src/lints.rs @@ -28,11 +28,11 @@ use crate::TypeCx; /// /// This is not used in the main algorithm; only in lints. #[derive(Debug)] -pub(crate) struct PatternColumn<'a, 'p, 'tcx> { - patterns: Vec<&'a DeconstructedPat<'p, 'tcx>>, +pub(crate) struct PatternColumn<'p, 'tcx> { + patterns: Vec<&'p DeconstructedPat<'p, 'tcx>>, } -impl<'a, 'p, 'tcx> PatternColumn<'a, 'p, 'tcx> { +impl<'p, 'tcx> PatternColumn<'p, 'tcx> { pub(crate) fn new(arms: &[MatchArm<'p, 'tcx>]) -> Self { let mut patterns = Vec::with_capacity(arms.len()); for arm in arms { @@ -48,7 +48,7 @@ impl<'a, 'p, 'tcx> PatternColumn<'a, 'p, 'tcx> { fn is_empty(&self) -> bool { self.patterns.is_empty() } - fn head_ty(&self, cx: MatchCtxt<'a, 'p, 'tcx>) -> Option> { + fn head_ty(&self, cx: MatchCtxt<'_, 'p, 'tcx>) -> Option> { if self.patterns.len() == 0 { return None; } @@ -64,7 +64,7 @@ impl<'a, 'p, 'tcx> PatternColumn<'a, 'p, 'tcx> { pcx.ctors_for_ty().split(pcx, column_ctors) } - fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { self.patterns.iter().copied() } @@ -75,9 +75,9 @@ impl<'a, 'p, 'tcx> PatternColumn<'a, 'p, 'tcx> { /// which may change the lengths. fn specialize( &self, - pcx: &PlaceCtxt<'a, 'p, 'tcx>, + pcx: &PlaceCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'p, 'tcx>, - ) -> Vec> { + ) -> Vec> { let arity = ctor.arity(pcx); if arity == 0 { return Vec::new(); @@ -115,7 +115,7 @@ impl<'a, 'p, 'tcx> PatternColumn<'a, 'p, 'tcx> { #[instrument(level = "debug", skip(cx), ret)] fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>( cx: MatchCtxt<'a, 'p, 'tcx>, - column: &PatternColumn<'a, 'p, 'tcx>, + column: &PatternColumn<'p, 'tcx>, ) -> Vec> { let Some(ty) = column.head_ty(cx) else { return Vec::new(); @@ -163,7 +163,7 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>( pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>( cx: MatchCtxt<'a, 'p, 'tcx>, arms: &[MatchArm<'p, 'tcx>], - pat_column: &PatternColumn<'a, 'p, 'tcx>, + pat_column: &PatternColumn<'p, 'tcx>, scrut_ty: Ty<'tcx>, ) { let rcx: &RustcMatchCheckCtxt<'_, '_> = cx.tycx; @@ -216,7 +216,7 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>( #[instrument(level = "debug", skip(cx))] pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>( cx: MatchCtxt<'a, 'p, 'tcx>, - column: &PatternColumn<'a, 'p, 'tcx>, + column: &PatternColumn<'p, 'tcx>, ) { let Some(ty) = column.head_ty(cx) else { return; diff --git a/compiler/rustc_pattern_analysis/src/pat.rs b/compiler/rustc_pattern_analysis/src/pat.rs index 9efd3e864dac0..70d829f236c2b 100644 --- a/compiler/rustc_pattern_analysis/src/pat.rs +++ b/compiler/rustc_pattern_analysis/src/pat.rs @@ -83,7 +83,7 @@ impl<'p, Cx: TypeCx> DeconstructedPat<'p, Cx> { &self, pcx: &PlaceCtxt<'a, 'p, Cx>, other_ctor: &Constructor, - ) -> SmallVec<[&'a DeconstructedPat<'p, Cx>; 2]> { + ) -> SmallVec<[&'p DeconstructedPat<'p, Cx>; 2]> { let wildcard_sub_tys = || { let tys = pcx.ctor_sub_tys(other_ctor); tys.iter() diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index b51b1a1f72255..fa3d72492045d 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -826,17 +826,17 @@ impl fmt::Display for ValidityConstraint { // - Cx global compilation context #[derive(derivative::Derivative)] #[derivative(Clone(bound = ""))] -struct PatStack<'a, 'p, Cx: TypeCx> { +struct PatStack<'p, Cx: TypeCx> { // Rows of len 1 are very common, which is why `SmallVec[_; 2]` works well. - pats: SmallVec<[&'a DeconstructedPat<'p, Cx>; 2]>, + pats: SmallVec<[&'p DeconstructedPat<'p, Cx>; 2]>, /// Sometimes we know that as far as this row is concerned, the current case is already handled /// by a different, more general, case. When the case is irrelevant for all rows this allows us /// to skip a case entirely. This is purely an optimization. See at the top for details. relevant: bool, } -impl<'a, 'p, Cx: TypeCx> PatStack<'a, 'p, Cx> { - fn from_pattern(pat: &'a DeconstructedPat<'p, Cx>) -> Self { +impl<'a, 'p, Cx: TypeCx> PatStack<'p, Cx> { + fn from_pattern(pat: &'p DeconstructedPat<'p, Cx>) -> Self { PatStack { pats: smallvec![pat], relevant: true } } @@ -848,17 +848,17 @@ impl<'a, 'p, Cx: TypeCx> PatStack<'a, 'p, Cx> { self.pats.len() } - fn head(&self) -> &'a DeconstructedPat<'p, Cx> { + fn head(&self) -> &'p DeconstructedPat<'p, Cx> { self.pats[0] } - fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { self.pats.iter().copied() } // Recursively expand the first or-pattern into its subpatterns. Only useful if the pattern is // an or-pattern. Panics if `self` is empty. - fn expand_or_pat<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn expand_or_pat<'b>(&'b self) -> impl Iterator> + Captures<'b> { self.head().flatten_or_pat().into_iter().map(move |pat| { let mut new = self.clone(); new.pats[0] = pat; @@ -873,7 +873,7 @@ impl<'a, 'p, Cx: TypeCx> PatStack<'a, 'p, Cx> { pcx: &PlaceCtxt<'a, 'p, Cx>, ctor: &Constructor, ctor_is_relevant: bool, - ) -> PatStack<'a, 'p, Cx> { + ) -> PatStack<'p, Cx> { // We pop the head pattern and push the new fields extracted from the arguments of // `self.head()`. let mut new_pats = self.head().specialize(pcx, ctor); @@ -886,7 +886,7 @@ impl<'a, 'p, Cx: TypeCx> PatStack<'a, 'p, Cx> { } } -impl<'a, 'p, Cx: TypeCx> fmt::Debug for PatStack<'a, 'p, Cx> { +impl<'p, Cx: TypeCx> fmt::Debug for PatStack<'p, Cx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // We pretty-print similarly to the `Debug` impl of `Matrix`. write!(f, "+")?; @@ -899,9 +899,9 @@ impl<'a, 'p, Cx: TypeCx> fmt::Debug for PatStack<'a, 'p, Cx> { /// A row of the matrix. #[derive(Clone)] -struct MatrixRow<'a, 'p, Cx: TypeCx> { +struct MatrixRow<'p, Cx: TypeCx> { // The patterns in the row. - pats: PatStack<'a, 'p, Cx>, + pats: PatStack<'p, Cx>, /// Whether the original arm had a guard. This is inherited when specializing. is_under_guard: bool, /// When we specialize, we remember which row of the original matrix produced a given row of the @@ -914,7 +914,7 @@ struct MatrixRow<'a, 'p, Cx: TypeCx> { useful: bool, } -impl<'a, 'p, Cx: TypeCx> MatrixRow<'a, 'p, Cx> { +impl<'a, 'p, Cx: TypeCx> MatrixRow<'p, Cx> { fn is_empty(&self) -> bool { self.pats.is_empty() } @@ -923,17 +923,17 @@ impl<'a, 'p, Cx: TypeCx> MatrixRow<'a, 'p, Cx> { self.pats.len() } - fn head(&self) -> &'a DeconstructedPat<'p, Cx> { + fn head(&self) -> &'p DeconstructedPat<'p, Cx> { self.pats.head() } - fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { self.pats.iter() } // Recursively expand the first or-pattern into its subpatterns. Only useful if the pattern is // an or-pattern. Panics if `self` is empty. - fn expand_or_pat<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn expand_or_pat<'b>(&'b self) -> impl Iterator> + Captures<'b> { self.pats.expand_or_pat().map(|patstack| MatrixRow { pats: patstack, parent_row: self.parent_row, @@ -950,7 +950,7 @@ impl<'a, 'p, Cx: TypeCx> MatrixRow<'a, 'p, Cx> { ctor: &Constructor, ctor_is_relevant: bool, parent_row: usize, - ) -> MatrixRow<'a, 'p, Cx> { + ) -> MatrixRow<'p, Cx> { MatrixRow { pats: self.pats.pop_head_constructor(pcx, ctor, ctor_is_relevant), parent_row, @@ -960,7 +960,7 @@ impl<'a, 'p, Cx: TypeCx> MatrixRow<'a, 'p, Cx> { } } -impl<'a, 'p, Cx: TypeCx> fmt::Debug for MatrixRow<'a, 'p, Cx> { +impl<'p, Cx: TypeCx> fmt::Debug for MatrixRow<'p, Cx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.pats.fmt(f) } @@ -977,22 +977,22 @@ impl<'a, 'p, Cx: TypeCx> fmt::Debug for MatrixRow<'a, 'p, Cx> { /// specializing `(,)` and `Some` on a pattern of type `(Option, bool)`, the first column of /// the matrix will correspond to `scrutinee.0.Some.0` and the second column to `scrutinee.1`. #[derive(Clone)] -struct Matrix<'a, 'p, Cx: TypeCx> { +struct Matrix<'p, Cx: TypeCx> { /// Vector of rows. The rows must form a rectangular 2D array. Moreover, all the patterns of /// each column must have the same type. Each column corresponds to a place within the /// scrutinee. - rows: Vec>, + rows: Vec>, /// Stores an extra fictitious row full of wildcards. Mostly used to keep track of the type of /// each column. This must obey the same invariants as the real rows. - wildcard_row: PatStack<'a, 'p, Cx>, + wildcard_row: PatStack<'p, Cx>, /// Track for each column/place whether it contains a known valid value. place_validity: SmallVec<[ValidityConstraint; 2]>, } -impl<'a, 'p, Cx: TypeCx> Matrix<'a, 'p, Cx> { +impl<'a, 'p, Cx: TypeCx> Matrix<'p, Cx> { /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively /// expands it. Internal method, prefer [`Matrix::new`]. - fn expand_and_push(&mut self, row: MatrixRow<'a, 'p, Cx>) { + fn expand_and_push(&mut self, row: MatrixRow<'p, Cx>) { if !row.is_empty() && row.head().is_or_pat() { // Expand nested or-patterns. for new_row in row.expand_or_pat() { @@ -1005,7 +1005,7 @@ impl<'a, 'p, Cx: TypeCx> Matrix<'a, 'p, Cx> { /// Build a new matrix from an iterator of `MatchArm`s. fn new( - wildcard_arena: &'a TypedArena>, + wildcard_arena: &'p TypedArena>, arms: &'a [MatchArm<'p, Cx>], scrut_ty: Cx::Ty, scrut_validity: ValidityConstraint, @@ -1044,13 +1044,13 @@ impl<'a, 'p, Cx: TypeCx> Matrix<'a, 'p, Cx> { fn rows<'b>( &'b self, - ) -> impl Iterator> + Clone + DoubleEndedIterator + ExactSizeIterator + ) -> impl Iterator> + Clone + DoubleEndedIterator + ExactSizeIterator { self.rows.iter() } fn rows_mut<'b>( &'b mut self, - ) -> impl Iterator> + DoubleEndedIterator + ExactSizeIterator + ) -> impl Iterator> + DoubleEndedIterator + ExactSizeIterator { self.rows.iter_mut() } @@ -1068,7 +1068,7 @@ impl<'a, 'p, Cx: TypeCx> Matrix<'a, 'p, Cx> { pcx: &PlaceCtxt<'a, 'p, Cx>, ctor: &Constructor, ctor_is_relevant: bool, - ) -> Matrix<'a, 'p, Cx> { + ) -> Matrix<'p, Cx> { let wildcard_row = self.wildcard_row.pop_head_constructor(pcx, ctor, ctor_is_relevant); let new_validity = self.place_validity[0].specialize(ctor); let new_place_validity = std::iter::repeat(new_validity) @@ -1097,7 +1097,7 @@ impl<'a, 'p, Cx: TypeCx> Matrix<'a, 'p, Cx> { /// + _ + [_, _, tail @ ..] + /// | ✓ | ? | // column validity /// ``` -impl<'a, 'p, Cx: TypeCx> fmt::Debug for Matrix<'a, 'p, Cx> { +impl<'p, Cx: TypeCx> fmt::Debug for Matrix<'p, Cx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\n")?; @@ -1336,7 +1336,7 @@ impl WitnessMatrix { #[instrument(level = "debug", skip(mcx, is_top_level), ret)] fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>( mcx: MatchCtxt<'a, 'p, Cx>, - matrix: &mut Matrix<'a, 'p, Cx>, + matrix: &mut Matrix<'p, Cx>, is_top_level: bool, ) -> WitnessMatrix { debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count())); From b91a98ba1062a8ec55721bb7ed824ae6985fdca1 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 26 Dec 2023 02:02:01 +0000 Subject: [PATCH 05/12] Even more --- compiler/rustc_pattern_analysis/src/rustc.rs | 2 +- .../rustc_pattern_analysis/src/usefulness.rs | 21 ++++++++----------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index a5a47724f3f02..1f5f8f2ce6d64 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -131,7 +131,7 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> { pub(crate) fn list_variant_nonhidden_fields<'a>( &'a self, ty: Ty<'tcx>, - variant: &'a VariantDef, + variant: &'a VariantDef, // TODO: ) -> impl Iterator)> + Captures<'p> + Captures<'a> { let cx = self; let ty::Adt(adt, args) = ty.kind() else { bug!() }; diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index fa3d72492045d..80210c6b97394 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -821,7 +821,6 @@ impl fmt::Display for ValidityConstraint { /// Represents a pattern-tuple under investigation. // The three lifetimes are: -// - 'a allocated by us // - 'p coming from the input // - Cx global compilation context #[derive(derivative::Derivative)] @@ -835,7 +834,7 @@ struct PatStack<'p, Cx: TypeCx> { relevant: bool, } -impl<'a, 'p, Cx: TypeCx> PatStack<'p, Cx> { +impl<'p, Cx: TypeCx> PatStack<'p, Cx> { fn from_pattern(pat: &'p DeconstructedPat<'p, Cx>) -> Self { PatStack { pats: smallvec![pat], relevant: true } } @@ -870,7 +869,7 @@ impl<'a, 'p, Cx: TypeCx> PatStack<'p, Cx> { /// Only call if `ctor.is_covered_by(self.head().ctor())` is true. fn pop_head_constructor( &self, - pcx: &PlaceCtxt<'a, 'p, Cx>, + pcx: &PlaceCtxt<'_, 'p, Cx>, ctor: &Constructor, ctor_is_relevant: bool, ) -> PatStack<'p, Cx> { @@ -914,7 +913,7 @@ struct MatrixRow<'p, Cx: TypeCx> { useful: bool, } -impl<'a, 'p, Cx: TypeCx> MatrixRow<'p, Cx> { +impl<'p, Cx: TypeCx> MatrixRow<'p, Cx> { fn is_empty(&self) -> bool { self.pats.is_empty() } @@ -946,7 +945,7 @@ impl<'a, 'p, Cx: TypeCx> MatrixRow<'p, Cx> { /// Only call if `ctor.is_covered_by(self.head().ctor())` is true. fn pop_head_constructor( &self, - pcx: &PlaceCtxt<'a, 'p, Cx>, + pcx: &PlaceCtxt<'_, 'p, Cx>, ctor: &Constructor, ctor_is_relevant: bool, parent_row: usize, @@ -989,7 +988,7 @@ struct Matrix<'p, Cx: TypeCx> { place_validity: SmallVec<[ValidityConstraint; 2]>, } -impl<'a, 'p, Cx: TypeCx> Matrix<'p, Cx> { +impl<'p, Cx: TypeCx> Matrix<'p, Cx> { /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively /// expands it. Internal method, prefer [`Matrix::new`]. fn expand_and_push(&mut self, row: MatrixRow<'p, Cx>) { @@ -1006,7 +1005,7 @@ impl<'a, 'p, Cx: TypeCx> Matrix<'p, Cx> { /// Build a new matrix from an iterator of `MatchArm`s. fn new( wildcard_arena: &'p TypedArena>, - arms: &'a [MatchArm<'p, Cx>], + arms: &[MatchArm<'p, Cx>], scrut_ty: Cx::Ty, scrut_validity: ValidityConstraint, ) -> Self { @@ -1029,7 +1028,7 @@ impl<'a, 'p, Cx: TypeCx> Matrix<'p, Cx> { matrix } - fn head_ty(&self, mcx: MatchCtxt<'a, 'p, Cx>) -> Option { + fn head_ty(&self, mcx: MatchCtxt<'_, 'p, Cx>) -> Option { if self.column_count() == 0 { return None; } @@ -1056,16 +1055,14 @@ impl<'a, 'p, Cx: TypeCx> Matrix<'p, Cx> { } /// Iterate over the first pattern of each row. - fn heads<'b>( - &'b self, - ) -> impl Iterator> + Clone + Captures<'a> { + fn heads<'b>(&'b self) -> impl Iterator> + Clone { self.rows().map(|r| r.head()) } /// This computes `specialize(ctor, self)`. See top of the file for explanations. fn specialize_constructor( &self, - pcx: &PlaceCtxt<'a, 'p, Cx>, + pcx: &PlaceCtxt<'_, 'p, Cx>, ctor: &Constructor, ctor_is_relevant: bool, ) -> Matrix<'p, Cx> { From ae40f6a7ffdda1f58794e25db2d8c9798cfe1e40 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 26 Dec 2023 02:06:39 +0000 Subject: [PATCH 06/12] Clean up more lifetimes --- compiler/rustc_pattern_analysis/src/constructor.rs | 7 ++----- compiler/rustc_pattern_analysis/src/pat.rs | 10 ++++------ compiler/rustc_pattern_analysis/src/rustc.rs | 8 ++++---- 3 files changed, 10 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_pattern_analysis/src/constructor.rs b/compiler/rustc_pattern_analysis/src/constructor.rs index b688051ca9ccb..15ff4ceb5b3a6 100644 --- a/compiler/rustc_pattern_analysis/src/constructor.rs +++ b/compiler/rustc_pattern_analysis/src/constructor.rs @@ -861,12 +861,9 @@ impl ConstructorSet { #[instrument(level = "debug", skip(self, pcx, ctors), ret)] pub(crate) fn split<'a>( &self, - pcx: &PlaceCtxt<'_, '_, Cx>, + pcx: &PlaceCtxt<'a, '_, Cx>, ctors: impl Iterator> + Clone, - ) -> SplitConstructorSet - where - Cx: 'a, - { + ) -> SplitConstructorSet { let mut present: SmallVec<[_; 1]> = SmallVec::new(); // Empty constructors found missing. let mut missing_empty = Vec::new(); diff --git a/compiler/rustc_pattern_analysis/src/pat.rs b/compiler/rustc_pattern_analysis/src/pat.rs index 70d829f236c2b..db41d2824a1ed 100644 --- a/compiler/rustc_pattern_analysis/src/pat.rs +++ b/compiler/rustc_pattern_analysis/src/pat.rs @@ -71,17 +71,15 @@ impl<'p, Cx: TypeCx> DeconstructedPat<'p, Cx> { self.data.as_ref() } - pub fn iter_fields<'a>( - &'a self, - ) -> impl Iterator> + Captures<'a> { + pub fn iter_fields(&self) -> impl Iterator> + Captures<'_> { self.fields.iter() } /// Specialize this pattern with a constructor. /// `other_ctor` can be different from `self.ctor`, but must be covered by it. - pub(crate) fn specialize<'a>( + pub(crate) fn specialize( &self, - pcx: &PlaceCtxt<'a, 'p, Cx>, + pcx: &PlaceCtxt<'_, 'p, Cx>, other_ctor: &Constructor, ) -> SmallVec<[&'p DeconstructedPat<'p, Cx>; 2]> { let wildcard_sub_tys = || { @@ -196,7 +194,7 @@ impl WitnessPat { self.ty } - pub fn iter_fields<'a>(&'a self) -> impl Iterator> { + pub fn iter_fields(&self) -> impl Iterator> { self.fields.iter() } } diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 1f5f8f2ce6d64..84aa6a0bbfdcd 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -128,11 +128,11 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> { // In the cases of either a `#[non_exhaustive]` field list or a non-public field, we hide // uninhabited fields in order not to reveal the uninhabitedness of the whole variant. // This lists the fields we keep along with their types. - pub(crate) fn list_variant_nonhidden_fields<'a>( - &'a self, + pub(crate) fn list_variant_nonhidden_fields( + &self, ty: Ty<'tcx>, - variant: &'a VariantDef, // TODO: - ) -> impl Iterator)> + Captures<'p> + Captures<'a> { + variant: &'tcx VariantDef, + ) -> impl Iterator)> + Captures<'p> + Captures<'_> { let cx = self; let ty::Adt(adt, args) = ty.kind() else { bug!() }; // Whether we must not match the fields of this variant exhaustively. From 4ae024c75489eca46dfacad5aa6f33023acce635 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 26 Dec 2023 02:12:33 +0000 Subject: [PATCH 07/12] Elide more lifetimes --- compiler/rustc_pattern_analysis/src/lints.rs | 2 +- .../rustc_pattern_analysis/src/usefulness.rs | 22 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_pattern_analysis/src/lints.rs b/compiler/rustc_pattern_analysis/src/lints.rs index e8b714204a3cf..e78cbd13822d1 100644 --- a/compiler/rustc_pattern_analysis/src/lints.rs +++ b/compiler/rustc_pattern_analysis/src/lints.rs @@ -64,7 +64,7 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> { pcx.ctors_for_ty().split(pcx, column_ctors) } - fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn iter(&self) -> impl Iterator> + Captures<'_> { self.patterns.iter().copied() } diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index 80210c6b97394..d2e621a6b98eb 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -851,13 +851,13 @@ impl<'p, Cx: TypeCx> PatStack<'p, Cx> { self.pats[0] } - fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn iter(&self) -> impl Iterator> + Captures<'_> { self.pats.iter().copied() } // Recursively expand the first or-pattern into its subpatterns. Only useful if the pattern is // an or-pattern. Panics if `self` is empty. - fn expand_or_pat<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn expand_or_pat(&self) -> impl Iterator> + Captures<'_> { self.head().flatten_or_pat().into_iter().map(move |pat| { let mut new = self.clone(); new.pats[0] = pat; @@ -926,13 +926,13 @@ impl<'p, Cx: TypeCx> MatrixRow<'p, Cx> { self.pats.head() } - fn iter<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn iter(&self) -> impl Iterator> + Captures<'_> { self.pats.iter() } // Recursively expand the first or-pattern into its subpatterns. Only useful if the pattern is // an or-pattern. Panics if `self` is empty. - fn expand_or_pat<'b>(&'b self) -> impl Iterator> + Captures<'b> { + fn expand_or_pat(&self) -> impl Iterator> + Captures<'_> { self.pats.expand_or_pat().map(|patstack| MatrixRow { pats: patstack, parent_row: self.parent_row, @@ -1041,21 +1041,21 @@ impl<'p, Cx: TypeCx> Matrix<'p, Cx> { self.wildcard_row.len() } - fn rows<'b>( - &'b self, - ) -> impl Iterator> + Clone + DoubleEndedIterator + ExactSizeIterator + fn rows( + &self, + ) -> impl Iterator> + Clone + DoubleEndedIterator + ExactSizeIterator { self.rows.iter() } - fn rows_mut<'b>( - &'b mut self, - ) -> impl Iterator> + DoubleEndedIterator + ExactSizeIterator + fn rows_mut( + &mut self, + ) -> impl Iterator> + DoubleEndedIterator + ExactSizeIterator { self.rows.iter_mut() } /// Iterate over the first pattern of each row. - fn heads<'b>(&'b self) -> impl Iterator> + Clone { + fn heads(&self) -> impl Iterator> + Clone + Captures<'_> { self.rows().map(|r| r.head()) } From 2b4f84f2b2312c5fe0f83fe457c79bd7fdc9ac15 Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Fri, 22 Dec 2023 20:33:37 +0100 Subject: [PATCH 08/12] `thir::Visitor` only needs to visit `&'thir` data --- compiler/rustc_middle/src/thir/visit.rs | 39 +++++++++++++------ .../rustc_mir_build/src/check_unsafety.rs | 8 ++-- .../src/thir/pattern/check_match.rs | 20 +++++----- compiler/rustc_ty_utils/src/consts.rs | 4 +- 4 files changed, 43 insertions(+), 28 deletions(-) diff --git a/compiler/rustc_middle/src/thir/visit.rs b/compiler/rustc_middle/src/thir/visit.rs index 4943c11848b8a..ade3ea289cc59 100644 --- a/compiler/rustc_middle/src/thir/visit.rs +++ b/compiler/rustc_middle/src/thir/visit.rs @@ -3,26 +3,26 @@ use super::{ PatKind, Stmt, StmtKind, Thir, }; -pub trait Visitor<'a, 'tcx: 'a>: Sized { - fn thir(&self) -> &'a Thir<'tcx>; +pub trait Visitor<'thir, 'tcx: 'thir>: Sized { + fn thir(&self) -> &'thir Thir<'tcx>; - fn visit_expr(&mut self, expr: &Expr<'tcx>) { + fn visit_expr(&mut self, expr: &'thir Expr<'tcx>) { walk_expr(self, expr); } - fn visit_stmt(&mut self, stmt: &Stmt<'tcx>) { + fn visit_stmt(&mut self, stmt: &'thir Stmt<'tcx>) { walk_stmt(self, stmt); } - fn visit_block(&mut self, block: &Block) { + fn visit_block(&mut self, block: &'thir Block) { walk_block(self, block); } - fn visit_arm(&mut self, arm: &Arm<'tcx>) { + fn visit_arm(&mut self, arm: &'thir Arm<'tcx>) { walk_arm(self, arm); } - fn visit_pat(&mut self, pat: &Pat<'tcx>) { + fn visit_pat(&mut self, pat: &'thir Pat<'tcx>) { walk_pat(self, pat); } @@ -36,7 +36,10 @@ pub trait Visitor<'a, 'tcx: 'a>: Sized { // other `visit*` functions. } -pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Expr<'tcx>) { +pub fn walk_expr<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( + visitor: &mut V, + expr: &'thir Expr<'tcx>, +) { use ExprKind::*; match expr.kind { Scope { value, region_scope: _, lint_level: _ } => { @@ -168,7 +171,10 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp } } -pub fn walk_stmt<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, stmt: &Stmt<'tcx>) { +pub fn walk_stmt<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( + visitor: &mut V, + stmt: &'thir Stmt<'tcx>, +) { match &stmt.kind { StmtKind::Expr { expr, scope: _ } => visitor.visit_expr(&visitor.thir()[*expr]), StmtKind::Let { @@ -191,7 +197,10 @@ pub fn walk_stmt<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, stmt: &Stm } } -pub fn walk_block<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, block: &Block) { +pub fn walk_block<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( + visitor: &mut V, + block: &'thir Block, +) { for &stmt in &*block.stmts { visitor.visit_stmt(&visitor.thir()[stmt]); } @@ -200,7 +209,10 @@ pub fn walk_block<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, block: &B } } -pub fn walk_arm<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, arm: &Arm<'tcx>) { +pub fn walk_arm<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( + visitor: &mut V, + arm: &'thir Arm<'tcx>, +) { match arm.guard { Some(Guard::If(expr)) => visitor.visit_expr(&visitor.thir()[expr]), Some(Guard::IfLet(ref pat, expr)) => { @@ -213,7 +225,10 @@ pub fn walk_arm<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, arm: &Arm<' visitor.visit_expr(&visitor.thir()[arm.body]); } -pub fn walk_pat<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, pat: &Pat<'tcx>) { +pub fn walk_pat<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( + visitor: &mut V, + pat: &'thir Pat<'tcx>, +) { use PatKind::*; match &pat.kind { AscribeUserType { subpattern, ascription: _ } diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 62190848dd55e..d529c5ea15983 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -175,7 +175,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> { self.thir } - fn visit_expr(&mut self, expr: &Expr<'tcx>) { + fn visit_expr(&mut self, expr: &'a Expr<'tcx>) { match expr.kind { ExprKind::Field { lhs, .. } => { if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() { @@ -206,7 +206,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { self.thir } - fn visit_block(&mut self, block: &Block) { + fn visit_block(&mut self, block: &'a Block) { match block.safety_mode { // compiler-generated unsafe code should not count towards the usefulness of // an outer unsafe block @@ -234,7 +234,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { } } - fn visit_pat(&mut self, pat: &Pat<'tcx>) { + fn visit_pat(&mut self, pat: &'a Pat<'tcx>) { if self.in_union_destructure { match pat.kind { // binding to a variable allows getting stuff out of variable @@ -319,7 +319,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { } } - fn visit_expr(&mut self, expr: &Expr<'tcx>) { + fn visit_expr(&mut self, expr: &'a Expr<'tcx>) { // could we be in the LHS of an assignment to a field? match expr.kind { ExprKind::Field { .. } 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 fcccdf105f649..0e85b3452d3f0 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -98,7 +98,7 @@ impl<'thir, 'tcx> Visitor<'thir, 'tcx> for MatchVisitor<'thir, '_, 'tcx> { } #[instrument(level = "trace", skip(self))] - fn visit_arm(&mut self, arm: &Arm<'tcx>) { + fn visit_arm(&mut self, arm: &'thir Arm<'tcx>) { self.with_lint_level(arm.lint_level, |this| { match arm.guard { Some(Guard::If(expr)) => { @@ -121,7 +121,7 @@ impl<'thir, 'tcx> Visitor<'thir, 'tcx> for MatchVisitor<'thir, '_, 'tcx> { } #[instrument(level = "trace", skip(self))] - fn visit_expr(&mut self, ex: &Expr<'tcx>) { + fn visit_expr(&mut self, ex: &'thir Expr<'tcx>) { match ex.kind { ExprKind::Scope { value, lint_level, .. } => { self.with_lint_level(lint_level, |this| { @@ -174,7 +174,7 @@ impl<'thir, 'tcx> Visitor<'thir, 'tcx> for MatchVisitor<'thir, '_, 'tcx> { self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex)); } - fn visit_stmt(&mut self, stmt: &Stmt<'tcx>) { + fn visit_stmt(&mut self, stmt: &'thir Stmt<'tcx>) { match stmt.kind { StmtKind::Let { box ref pattern, initializer, else_block, lint_level, span, .. @@ -224,7 +224,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { /// subexpressions we are not handling ourselves. fn visit_land( &mut self, - ex: &Expr<'tcx>, + ex: &'thir Expr<'tcx>, accumulator: &mut Vec>, ) -> Result<(), ErrorGuaranteed> { match ex.kind { @@ -251,7 +251,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { /// expression. This must call `visit_expr` on the subexpressions we are not handling ourselves. fn visit_land_rhs( &mut self, - ex: &Expr<'tcx>, + ex: &'thir Expr<'tcx>, ) -> Result, ErrorGuaranteed> { match ex.kind { ExprKind::Scope { value, lint_level, .. } => { @@ -276,7 +276,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { fn lower_pattern( &mut self, cx: &MatchCheckCtxt<'p, 'tcx>, - pat: &Pat<'tcx>, + pat: &'thir Pat<'tcx>, ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> { if let Err(err) = pat.pat_error_reported() { self.error = Err(err); @@ -395,7 +395,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { } #[instrument(level = "trace", skip(self))] - fn check_let(&mut self, pat: &Pat<'tcx>, scrutinee: Option, span: Span) { + fn check_let(&mut self, pat: &'thir Pat<'tcx>, scrutinee: Option, span: Span) { assert!(self.let_source != LetSource::None); let scrut = scrutinee.map(|id| &self.thir[id]); if let LetSource::PlainLet = self.let_source { @@ -547,7 +547,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { fn analyze_binding( &mut self, - pat: &Pat<'tcx>, + pat: &'thir Pat<'tcx>, refutability: RefutableFlag, scrut: Option<&Expr<'tcx>>, ) -> Result<(MatchCheckCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> { @@ -560,7 +560,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { fn is_let_irrefutable( &mut self, - pat: &Pat<'tcx>, + pat: &'thir Pat<'tcx>, scrut: Option<&Expr<'tcx>>, ) -> Result { let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?; @@ -575,7 +575,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { #[instrument(level = "trace", skip(self))] fn check_binding_is_irrefutable( &mut self, - pat: &Pat<'tcx>, + pat: &'thir Pat<'tcx>, origin: &str, scrut: Option<&Expr<'tcx>>, sp: Option, diff --git a/compiler/rustc_ty_utils/src/consts.rs b/compiler/rustc_ty_utils/src/consts.rs index b521a5c1145f6..0805891869ef3 100644 --- a/compiler/rustc_ty_utils/src/consts.rs +++ b/compiler/rustc_ty_utils/src/consts.rs @@ -379,7 +379,7 @@ impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> { } #[instrument(skip(self), level = "debug")] - fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) { + fn visit_expr(&mut self, expr: &'a thir::Expr<'tcx>) { self.is_poly |= self.expr_is_poly(expr); if !self.is_poly { visit::walk_expr(self, expr) @@ -387,7 +387,7 @@ impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> { } #[instrument(skip(self), level = "debug")] - fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) { + fn visit_pat(&mut self, pat: &'a thir::Pat<'tcx>) { self.is_poly |= self.pat_is_poly(pat); if !self.is_poly { visit::walk_pat(self, pat); From 48d089a8002d57f0c7b473905bc1925e99bcc76d Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 26 Dec 2023 03:12:48 +0000 Subject: [PATCH 09/12] Merge 'thir and 'p --- .../src/thir/pattern/check_match.rs | 34 +++++++++---------- compiler/rustc_pattern_analysis/src/rustc.rs | 2 +- 2 files changed, 18 insertions(+), 18 deletions(-) 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 0e85b3452d3f0..c8e5b934bebd5 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -75,11 +75,11 @@ enum LetSource { WhileLet, } -struct MatchVisitor<'thir, 'p, 'tcx> { +struct MatchVisitor<'p, 'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, typeck_results: &'tcx ty::TypeckResults<'tcx>, - thir: &'thir Thir<'tcx>, + thir: &'p Thir<'tcx>, lint_level: HirId, let_source: LetSource, pattern_arena: &'p TypedArena>, @@ -92,13 +92,13 @@ struct MatchVisitor<'thir, 'p, 'tcx> { // Visitor for a thir body. This calls `check_match`, `check_let` and `check_let_chain` as // appropriate. -impl<'thir, 'tcx> Visitor<'thir, 'tcx> for MatchVisitor<'thir, '_, 'tcx> { - fn thir(&self) -> &'thir Thir<'tcx> { +impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> { + fn thir(&self) -> &'p Thir<'tcx> { self.thir } #[instrument(level = "trace", skip(self))] - fn visit_arm(&mut self, arm: &'thir Arm<'tcx>) { + fn visit_arm(&mut self, arm: &'p Arm<'tcx>) { self.with_lint_level(arm.lint_level, |this| { match arm.guard { Some(Guard::If(expr)) => { @@ -121,7 +121,7 @@ impl<'thir, 'tcx> Visitor<'thir, 'tcx> for MatchVisitor<'thir, '_, 'tcx> { } #[instrument(level = "trace", skip(self))] - fn visit_expr(&mut self, ex: &'thir Expr<'tcx>) { + fn visit_expr(&mut self, ex: &'p Expr<'tcx>) { match ex.kind { ExprKind::Scope { value, lint_level, .. } => { self.with_lint_level(lint_level, |this| { @@ -174,7 +174,7 @@ impl<'thir, 'tcx> Visitor<'thir, 'tcx> for MatchVisitor<'thir, '_, 'tcx> { self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex)); } - fn visit_stmt(&mut self, stmt: &'thir Stmt<'tcx>) { + fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) { match stmt.kind { StmtKind::Let { box ref pattern, initializer, else_block, lint_level, span, .. @@ -195,7 +195,7 @@ impl<'thir, 'tcx> Visitor<'thir, 'tcx> for MatchVisitor<'thir, '_, 'tcx> { } } -impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { +impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { #[instrument(level = "trace", skip(self, f))] fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) { let old_let_source = self.let_source; @@ -224,7 +224,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { /// subexpressions we are not handling ourselves. fn visit_land( &mut self, - ex: &'thir Expr<'tcx>, + ex: &'p Expr<'tcx>, accumulator: &mut Vec>, ) -> Result<(), ErrorGuaranteed> { match ex.kind { @@ -251,7 +251,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { /// expression. This must call `visit_expr` on the subexpressions we are not handling ourselves. fn visit_land_rhs( &mut self, - ex: &'thir Expr<'tcx>, + ex: &'p Expr<'tcx>, ) -> Result, ErrorGuaranteed> { match ex.kind { ExprKind::Scope { value, lint_level, .. } => { @@ -276,7 +276,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { fn lower_pattern( &mut self, cx: &MatchCheckCtxt<'p, 'tcx>, - pat: &'thir Pat<'tcx>, + pat: &'p Pat<'tcx>, ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> { if let Err(err) = pat.pat_error_reported() { self.error = Err(err); @@ -395,7 +395,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { } #[instrument(level = "trace", skip(self))] - fn check_let(&mut self, pat: &'thir Pat<'tcx>, scrutinee: Option, span: Span) { + fn check_let(&mut self, pat: &'p Pat<'tcx>, scrutinee: Option, span: Span) { assert!(self.let_source != LetSource::None); let scrut = scrutinee.map(|id| &self.thir[id]); if let LetSource::PlainLet = self.let_source { @@ -547,7 +547,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { fn analyze_binding( &mut self, - pat: &'thir Pat<'tcx>, + pat: &'p Pat<'tcx>, refutability: RefutableFlag, scrut: Option<&Expr<'tcx>>, ) -> Result<(MatchCheckCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> { @@ -560,7 +560,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { fn is_let_irrefutable( &mut self, - pat: &'thir Pat<'tcx>, + pat: &'p Pat<'tcx>, scrut: Option<&Expr<'tcx>>, ) -> Result { let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?; @@ -575,7 +575,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { #[instrument(level = "trace", skip(self))] fn check_binding_is_irrefutable( &mut self, - pat: &'thir Pat<'tcx>, + pat: &'p Pat<'tcx>, origin: &str, scrut: Option<&Expr<'tcx>>, sp: Option, @@ -677,7 +677,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> { /// - `x @ Some(ref mut? y)`. /// /// This analysis is *not* subsumed by NLL. -fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, '_, 'tcx>, pat: &Pat<'tcx>) { +fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, 'tcx>, pat: &Pat<'tcx>) { // Extract `sub` in `binding @ sub`. let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else { return; @@ -772,7 +772,7 @@ fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, '_, 'tcx>, } fn check_for_bindings_named_same_as_variants( - cx: &MatchVisitor<'_, '_, '_>, + cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>, rf: RefutableFlag, ) { diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 84aa6a0bbfdcd..e9922f621b774 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -399,7 +399,7 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> { /// Note: the input patterns must have been lowered through /// `rustc_mir_build::thir::pattern::check_match::MatchVisitor::lower_pattern`. - pub fn lower_pat(&self, pat: &Pat<'tcx>) -> DeconstructedPat<'p, 'tcx> { + pub fn lower_pat(&self, pat: &'p Pat<'tcx>) -> DeconstructedPat<'p, 'tcx> { let singleton = |pat| std::slice::from_ref(self.pattern_arena.alloc(pat)); let cx = self; let ctor; From 7e00e9736db89ecef7575622a13b57021ec34493 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 23 Dec 2023 04:02:17 +0000 Subject: [PATCH 10/12] Make some non-diagnostic-affecting QPath::LangItem into regular qpaths --- compiler/rustc_ast_lowering/src/expr.rs | 10 ++++------ compiler/rustc_ast_lowering/src/lib.rs | 6 +++++- .../clippy/tests/ui/author/macro_in_closure.stdout | 2 ++ src/tools/clippy/tests/ui/author/macro_in_loop.stdout | 2 ++ tests/pretty/issue-4264.pp | 2 +- tests/ui/unpretty/flattened-format-args.stdout | 5 ++--- 6 files changed, 16 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 1f6d47ab4535b..f0e2c59eb3fa7 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -639,7 +639,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.lower_span(span), Some(self.allow_gen_future.clone()), ); - let resume_ty = hir::QPath::LangItem(hir::LangItem::ResumeTy, unstable_span); + let resume_ty = self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span); let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Path(resume_ty), @@ -777,7 +777,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.lower_span(span), Some(self.allow_gen_future.clone()), ); - let resume_ty = hir::QPath::LangItem(hir::LangItem::ResumeTy, unstable_span); + let resume_ty = self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span); let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Path(resume_ty), @@ -2116,11 +2116,9 @@ impl<'hir> LoweringContext<'_, 'hir> { lang_item: hir::LangItem, name: Symbol, ) -> hir::Expr<'hir> { + let qpath = self.make_lang_item_qpath(lang_item, self.lower_span(span)); let path = hir::ExprKind::Path(hir::QPath::TypeRelative( - self.arena.alloc(self.ty( - span, - hir::TyKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span))), - )), + self.arena.alloc(self.ty(span, hir::TyKind::Path(qpath))), self.arena.alloc(hir::PathSegment::new( Ident::new(name, span), self.next_id(), diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index e35d7d62cad48..73ac324d8d0ed 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -766,6 +766,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.resolver.get_import_res(id).present_items() } + fn make_lang_item_qpath(&mut self, lang_item: hir::LangItem, span: Span) -> hir::QPath<'hir> { + hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, None)) + } + fn make_lang_item_path( &mut self, lang_item: hir::LangItem, @@ -783,7 +787,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir_id: self.next_id(), res, args, - infer_args: false, + infer_args: args.is_none(), }]), }) } diff --git a/src/tools/clippy/tests/ui/author/macro_in_closure.stdout b/src/tools/clippy/tests/ui/author/macro_in_closure.stdout index 9ab71986f40f4..5a2542c8628ae 100644 --- a/src/tools/clippy/tests/ui/author/macro_in_closure.stdout +++ b/src/tools/clippy/tests/ui/author/macro_in_closure.stdout @@ -12,6 +12,7 @@ if let StmtKind::Local(local) = stmt.kind && args.len() == 1 && let ExprKind::Call(func1, args1) = args[0].kind && let ExprKind::Path(ref qpath1) = func1.kind + && match_qpath(qpath1, &["format_arguments", "new_v1"]) && args1.len() == 2 && let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = args1[0].kind && let ExprKind::Array(elements) = inner.kind @@ -27,6 +28,7 @@ if let StmtKind::Local(local) = stmt.kind && elements1.len() == 1 && let ExprKind::Call(func2, args2) = elements1[0].kind && let ExprKind::Path(ref qpath2) = func2.kind + && match_qpath(qpath2, &["format_argument", "new_display"]) && args2.len() == 1 && let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner2) = args2[0].kind && let ExprKind::Path(ref qpath3) = inner2.kind diff --git a/src/tools/clippy/tests/ui/author/macro_in_loop.stdout b/src/tools/clippy/tests/ui/author/macro_in_loop.stdout index bd054b6abc438..a719e3af7e76b 100644 --- a/src/tools/clippy/tests/ui/author/macro_in_loop.stdout +++ b/src/tools/clippy/tests/ui/author/macro_in_loop.stdout @@ -22,6 +22,7 @@ if let Some(higher::ForLoop { pat: pat, arg: arg, body: body, .. }) = higher::Fo && args.len() == 1 && let ExprKind::Call(func1, args1) = args[0].kind && let ExprKind::Path(ref qpath2) = func1.kind + && match_qpath(qpath2, &["format_arguments", "new_v1"]) && args1.len() == 2 && let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = args1[0].kind && let ExprKind::Array(elements) = inner.kind @@ -37,6 +38,7 @@ if let Some(higher::ForLoop { pat: pat, arg: arg, body: body, .. }) = higher::Fo && elements1.len() == 1 && let ExprKind::Call(func2, args2) = elements1[0].kind && let ExprKind::Path(ref qpath3) = func2.kind + && match_qpath(qpath3, &["format_argument", "new_display"]) && args2.len() == 1 && let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner2) = args2[0].kind && let ExprKind::Path(ref qpath4) = inner2.kind diff --git a/tests/pretty/issue-4264.pp b/tests/pretty/issue-4264.pp index 4020a433d6254..2d713832dcd3d 100644 --- a/tests/pretty/issue-4264.pp +++ b/tests/pretty/issue-4264.pp @@ -32,7 +32,7 @@ ({ let res = ((::alloc::fmt::format as - for<'a> fn(Arguments<'a>) -> String {format})(((<#[lang = "format_arguments"]>::new_const + for<'a> fn(Arguments<'a>) -> String {format})(((format_arguments::new_const as fn(&[&'static str]) -> Arguments<'_> {Arguments::<'_>::new_const})((&([("test" as &str)] as [&str; 1]) as &[&str; 1])) as Arguments<'_>)) diff --git a/tests/ui/unpretty/flattened-format-args.stdout b/tests/ui/unpretty/flattened-format-args.stdout index a8fe8da002472..7fc5d26605996 100644 --- a/tests/ui/unpretty/flattened-format-args.stdout +++ b/tests/ui/unpretty/flattened-format-args.stdout @@ -9,8 +9,7 @@ fn main() { let x = 1; // Should flatten to println!("a 123 b {x} xyz\n"): { - ::std::io::_print(<#[lang = "format_arguments"]>::new_v1(&["a 123 b ", - " xyz\n"], - &[<#[lang = "format_argument"]>::new_display(&x)])); + ::std::io::_print(format_arguments::new_v1(&["a 123 b ", + " xyz\n"], &[format_argument::new_display(&x)])); }; } From cb2fc0967fbecc26a33dcc9b99bbeccc826d576b Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Tue, 26 Dec 2023 17:50:30 +0100 Subject: [PATCH 11/12] rename tests --- .../ui/sized/{recursive-type-2.rs => recursive-type-binding.rs} | 0 .../{recursive-type-2.stderr => recursive-type-binding.stderr} | 2 +- tests/ui/sized/{recursive-type-1.rs => recursive-type-pass.rs} | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename tests/ui/sized/{recursive-type-2.rs => recursive-type-binding.rs} (100%) rename tests/ui/sized/{recursive-type-2.stderr => recursive-type-binding.stderr} (93%) rename tests/ui/sized/{recursive-type-1.rs => recursive-type-pass.rs} (100%) diff --git a/tests/ui/sized/recursive-type-2.rs b/tests/ui/sized/recursive-type-binding.rs similarity index 100% rename from tests/ui/sized/recursive-type-2.rs rename to tests/ui/sized/recursive-type-binding.rs diff --git a/tests/ui/sized/recursive-type-2.stderr b/tests/ui/sized/recursive-type-binding.stderr similarity index 93% rename from tests/ui/sized/recursive-type-2.stderr rename to tests/ui/sized/recursive-type-binding.stderr index 4e7f40a01533c..d9c2efa4d53b7 100644 --- a/tests/ui/sized/recursive-type-2.stderr +++ b/tests/ui/sized/recursive-type-binding.stderr @@ -3,7 +3,7 @@ error[E0391]: cycle detected when computing layout of `Foo<()>` = note: ...which requires computing layout of `<() as A>::Assoc`... = note: ...which again requires computing layout of `Foo<()>`, completing the cycle note: cycle used when elaborating drops for `main` - --> $DIR/recursive-type-2.rs:11:1 + --> $DIR/recursive-type-binding.rs:11:1 | LL | fn main() { | ^^^^^^^^^ diff --git a/tests/ui/sized/recursive-type-1.rs b/tests/ui/sized/recursive-type-pass.rs similarity index 100% rename from tests/ui/sized/recursive-type-1.rs rename to tests/ui/sized/recursive-type-pass.rs From 29036045c3d156e2e952732c61034ec0c00f5903 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Tue, 26 Dec 2023 17:50:41 +0100 Subject: [PATCH 12/12] add test for coercing never to infinite type --- .../sized/recursive-type-coercion-from-never.rs | 16 ++++++++++++++++ .../recursive-type-coercion-from-never.stderr | 14 ++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tests/ui/sized/recursive-type-coercion-from-never.rs create mode 100644 tests/ui/sized/recursive-type-coercion-from-never.stderr diff --git a/tests/ui/sized/recursive-type-coercion-from-never.rs b/tests/ui/sized/recursive-type-coercion-from-never.rs new file mode 100644 index 0000000000000..a1b654637316d --- /dev/null +++ b/tests/ui/sized/recursive-type-coercion-from-never.rs @@ -0,0 +1,16 @@ +// build-fail +//~^ ERROR cycle detected when computing layout of `Foo<()>` + +// Regression test for a stack overflow: https://github.com/rust-lang/rust/issues/113197 + +trait A { type Assoc; } + +impl A for () { + type Assoc = Foo<()>; +} + +struct Foo(T::Assoc); + +fn main() { + Foo::<()>(todo!()); +} diff --git a/tests/ui/sized/recursive-type-coercion-from-never.stderr b/tests/ui/sized/recursive-type-coercion-from-never.stderr new file mode 100644 index 0000000000000..7580e780dda59 --- /dev/null +++ b/tests/ui/sized/recursive-type-coercion-from-never.stderr @@ -0,0 +1,14 @@ +error[E0391]: cycle detected when computing layout of `Foo<()>` + | + = note: ...which requires computing layout of `<() as A>::Assoc`... + = note: ...which again requires computing layout of `Foo<()>`, completing the cycle +note: cycle used when elaborating drops for `main` + --> $DIR/recursive-type-coercion-from-never.rs:14:1 + | +LL | fn main() { + | ^^^^^^^^^ + = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0391`.