From 6d569f769c3d7becbd566b4fec5baf9f11e098e1 Mon Sep 17 00:00:00 2001 From: Ding Xiang Fei Date: Mon, 21 Oct 2024 05:06:30 +0800 Subject: [PATCH 01/17] stabilize if_let_rescope --- compiler/rustc_feature/src/accepted.rs | 2 ++ compiler/rustc_feature/src/unstable.rs | 2 -- .../rustc_hir_analysis/src/check/region.rs | 6 ++--- compiler/rustc_lint/src/if_let_rescope.rs | 3 +-- compiler/rustc_mir_build/src/thir/cx/expr.rs | 2 +- tests/ui/drop/drop_order.rs | 2 +- tests/ui/drop/drop_order_if_let_rescope.rs | 1 - .../if-let-rescope-borrowck-suggestions.rs | 1 - ...if-let-rescope-borrowck-suggestions.stderr | 12 ++++----- ...t-if-let-rescope-gated.edition2021.stderr} | 0 tests/ui/drop/lint-if-let-rescope-gated.rs | 22 +++++++-------- .../ui/drop/lint-if-let-rescope-with-macro.rs | 1 - .../lint-if-let-rescope-with-macro.stderr | 6 ++--- tests/ui/drop/lint-if-let-rescope.fixed | 2 +- tests/ui/drop/lint-if-let-rescope.rs | 2 +- .../feature-gate-if-let-rescope.rs | 27 ------------------- .../feature-gate-if-let-rescope.stderr | 18 ------------- tests/ui/mir/mir_let_chains_drop_order.rs | 1 - .../issue-54556-niconii.edition2021.stderr | 2 +- tests/ui/nll/issue-54556-niconii.rs | 2 -- 20 files changed, 30 insertions(+), 84 deletions(-) rename tests/ui/drop/{lint-if-let-rescope-gated.with_feature_gate.stderr => lint-if-let-rescope-gated.edition2021.stderr} (100%) delete mode 100644 tests/ui/feature-gates/feature-gate-if-let-rescope.rs delete mode 100644 tests/ui/feature-gates/feature-gate-if-let-rescope.stderr diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 4f71bdaca1b13..95b33890d69ee 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -224,6 +224,8 @@ declare_features! ( (accepted, i128_type, "1.26.0", Some(35118)), /// Allows the use of `if let` expressions. (accepted, if_let, "1.0.0", None), + /// Rescoping temporaries in `if let` to align with Rust 2024. + (accepted, if_let_rescope, "CURRENT_RUSTC_VERSION", Some(124085)), /// Allows top level or-patterns (`p | q`) in `if let` and `while let`. (accepted, if_while_or_patterns, "1.33.0", Some(48215)), /// Allows lifetime elision in `impl` headers. For example: diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 8f4c208f1fbb5..63c43c41ca699 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -482,8 +482,6 @@ declare_features! ( (unstable, half_open_range_patterns_in_slices, "1.66.0", Some(67264)), /// Allows `if let` guard in match arms. (unstable, if_let_guard, "1.47.0", Some(51114)), - /// Rescoping temporaries in `if let` to align with Rust 2024. - (unstable, if_let_rescope, "1.83.0", Some(124085)), /// Allows `impl Trait` to be used inside associated types (RFC 2515). (unstable, impl_trait_in_assoc_type, "1.70.0", Some(63063)), /// Allows `impl Trait` as output type in `Fn` traits in return position of functions. diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 312fb16c93aae..e37a7ed295245 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -466,8 +466,7 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h hir::ExprKind::If(cond, then, Some(otherwise)) => { let expr_cx = visitor.cx; - let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope() - { + let data = if expr.span.at_least_rust_2024() { ScopeData::IfThenRescope } else { ScopeData::IfThen @@ -482,8 +481,7 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h hir::ExprKind::If(cond, then, None) => { let expr_cx = visitor.cx; - let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope() - { + let data = if expr.span.at_least_rust_2024() { ScopeData::IfThenRescope } else { ScopeData::IfThen diff --git a/compiler/rustc_lint/src/if_let_rescope.rs b/compiler/rustc_lint/src/if_let_rescope.rs index bdfcc2c0a1006..afcfbebc14b31 100644 --- a/compiler/rustc_lint/src/if_let_rescope.rs +++ b/compiler/rustc_lint/src/if_let_rescope.rs @@ -24,7 +24,6 @@ declare_lint! { /// ### Example /// /// ```rust,edition2021 - /// #![feature(if_let_rescope)] /// #![warn(if_let_rescope)] /// #![allow(unused_variables)] /// @@ -243,7 +242,7 @@ impl_lint_pass!( impl<'tcx> LateLintPass<'tcx> for IfLetRescope { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { - if expr.span.edition().at_least_rust_2024() || !cx.tcx.features().if_let_rescope() { + if expr.span.edition().at_least_rust_2024() { return; } if let (Level::Allow, _) = cx.tcx.lint_level_at_node(IF_LET_RESCOPE, expr.hir_id) { diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 5faefe2f25f41..24c914da77a0f 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -777,7 +777,7 @@ impl<'tcx> Cx<'tcx> { if_then_scope: region::Scope { id: then.hir_id.local_id, data: { - if expr.span.at_least_rust_2024() && tcx.features().if_let_rescope() { + if expr.span.at_least_rust_2024() { region::ScopeData::IfThenRescope } else { region::ScopeData::IfThen diff --git a/tests/ui/drop/drop_order.rs b/tests/ui/drop/drop_order.rs index cf06253800745..9706cb66b19df 100644 --- a/tests/ui/drop/drop_order.rs +++ b/tests/ui/drop/drop_order.rs @@ -4,8 +4,8 @@ //@ [edition2021] edition: 2021 //@ [edition2024] compile-flags: -Z unstable-options //@ [edition2024] edition: 2024 + #![feature(let_chains)] -#![cfg_attr(edition2024, feature(if_let_rescope))] use std::cell::RefCell; use std::convert::TryInto; diff --git a/tests/ui/drop/drop_order_if_let_rescope.rs b/tests/ui/drop/drop_order_if_let_rescope.rs index ae9f381820e16..cea84bbaa2b92 100644 --- a/tests/ui/drop/drop_order_if_let_rescope.rs +++ b/tests/ui/drop/drop_order_if_let_rescope.rs @@ -3,7 +3,6 @@ //@ compile-flags: -Z validate-mir -Zunstable-options #![feature(let_chains)] -#![feature(if_let_rescope)] use std::cell::RefCell; use std::convert::TryInto; diff --git a/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs b/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs index 2476f7cf2580a..e055c20d777bc 100644 --- a/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs +++ b/tests/ui/drop/if-let-rescope-borrowck-suggestions.rs @@ -1,7 +1,6 @@ //@ edition: 2024 //@ compile-flags: -Z validate-mir -Zunstable-options -#![feature(if_let_rescope)] #![deny(if_let_rescope)] struct Droppy; diff --git a/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr b/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr index 0c6f1ea28d2ae..3c87e196af6e5 100644 --- a/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr +++ b/tests/ui/drop/if-let-rescope-borrowck-suggestions.stderr @@ -1,5 +1,5 @@ error[E0716]: temporary value dropped while borrowed - --> $DIR/if-let-rescope-borrowck-suggestions.rs:22:39 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:21:39 | LL | do_something(if let Some(value) = Droppy.get_ref() { value } else { &0 }); | ^^^^^^ - temporary value is freed at the end of this statement @@ -7,7 +7,7 @@ LL | do_something(if let Some(value) = Droppy.get_ref() { value } else { &0 | creates a temporary value which is freed while still in use | note: lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead - --> $DIR/if-let-rescope-borrowck-suggestions.rs:22:64 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:21:64 | LL | do_something(if let Some(value) = Droppy.get_ref() { value } else { &0 }); | ^ @@ -22,7 +22,7 @@ LL | do_something({ match Droppy.get_ref() { Some(value) => { value } _ => | ~~~~~~~ ++++++++++++++++ ~~~~ ++ error[E0716]: temporary value dropped while borrowed - --> $DIR/if-let-rescope-borrowck-suggestions.rs:24:39 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:23:39 | LL | do_something(if let Some(value) = Droppy.get_ref() { | ^^^^^^ creates a temporary value which is freed while still in use @@ -31,7 +31,7 @@ LL | } else if let Some(value) = Droppy.get_ref() { | - temporary value is freed at the end of this statement | note: lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead - --> $DIR/if-let-rescope-borrowck-suggestions.rs:27:5 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:26:5 | LL | } else if let Some(value) = Droppy.get_ref() { | ^ @@ -53,7 +53,7 @@ LL ~ }}}); | error[E0716]: temporary value dropped while borrowed - --> $DIR/if-let-rescope-borrowck-suggestions.rs:27:33 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:26:33 | LL | } else if let Some(value) = Droppy.get_ref() { | ^^^^^^ creates a temporary value which is freed while still in use @@ -62,7 +62,7 @@ LL | } else { | - temporary value is freed at the end of this statement | note: lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead - --> $DIR/if-let-rescope-borrowck-suggestions.rs:30:5 + --> $DIR/if-let-rescope-borrowck-suggestions.rs:29:5 | LL | } else { | ^ diff --git a/tests/ui/drop/lint-if-let-rescope-gated.with_feature_gate.stderr b/tests/ui/drop/lint-if-let-rescope-gated.edition2021.stderr similarity index 100% rename from tests/ui/drop/lint-if-let-rescope-gated.with_feature_gate.stderr rename to tests/ui/drop/lint-if-let-rescope-gated.edition2021.stderr diff --git a/tests/ui/drop/lint-if-let-rescope-gated.rs b/tests/ui/drop/lint-if-let-rescope-gated.rs index cef5de5a8fe56..ba0246573b406 100644 --- a/tests/ui/drop/lint-if-let-rescope-gated.rs +++ b/tests/ui/drop/lint-if-let-rescope-gated.rs @@ -1,13 +1,13 @@ // This test checks that the lint `if_let_rescope` only actions -// when the feature gate is enabled. -// Edition 2021 is used here because the lint should work especially -// when edition migration towards 2024 is run. +// when Edition 2021 or prior is targeted here because the lint should work especially +// when edition migration towards 2024 is executed. -//@ revisions: with_feature_gate without_feature_gate -//@ [without_feature_gate] check-pass -//@ edition: 2021 +//@ revisions: edition2021 edition2024 +//@ [edition2021] edition: 2021 +//@ [edition2024] edition: 2024 +//@ [edition2024] compile-flags: -Zunstable-options +//@ [edition2024] check-pass -#![cfg_attr(with_feature_gate, feature(if_let_rescope))] #![deny(if_let_rescope)] #![allow(irrefutable_let_patterns)] @@ -25,10 +25,10 @@ impl Droppy { fn main() { if let Some(_value) = Droppy.get() { - //[with_feature_gate]~^ ERROR: `if let` assigns a shorter lifetime since Edition 2024 - //[with_feature_gate]~| HELP: a `match` with a single arm can preserve the drop order up to Edition 2021 - //[with_feature_gate]~| WARN: this changes meaning in Rust 2024 + //[edition2021]~^ ERROR: `if let` assigns a shorter lifetime since Edition 2024 + //[edition2021]~| HELP: a `match` with a single arm can preserve the drop order up to Edition 2021 + //[edition2021]~| WARN: this changes meaning in Rust 2024 } else { - //[with_feature_gate]~^ HELP: the value is now dropped here in Edition 2024 + //[edition2021]~^ HELP: the value is now dropped here in Edition 2024 } } diff --git a/tests/ui/drop/lint-if-let-rescope-with-macro.rs b/tests/ui/drop/lint-if-let-rescope-with-macro.rs index 282b3320d3004..e7aeb81f4d1a5 100644 --- a/tests/ui/drop/lint-if-let-rescope-with-macro.rs +++ b/tests/ui/drop/lint-if-let-rescope-with-macro.rs @@ -4,7 +4,6 @@ //@ edition:2021 //@ compile-flags: -Z unstable-options -#![feature(if_let_rescope)] #![deny(if_let_rescope)] #![allow(irrefutable_let_patterns)] diff --git a/tests/ui/drop/lint-if-let-rescope-with-macro.stderr b/tests/ui/drop/lint-if-let-rescope-with-macro.stderr index 5fd0c61d17a57..de6cf6e8500ee 100644 --- a/tests/ui/drop/lint-if-let-rescope-with-macro.stderr +++ b/tests/ui/drop/lint-if-let-rescope-with-macro.stderr @@ -1,5 +1,5 @@ error: `if let` assigns a shorter lifetime since Edition 2024 - --> $DIR/lint-if-let-rescope-with-macro.rs:13:12 + --> $DIR/lint-if-let-rescope-with-macro.rs:12:12 | LL | if let $p = $e { $($conseq)* } else { $($alt)* } | ^^^ @@ -16,7 +16,7 @@ LL | | }; = warning: this changes meaning in Rust 2024 = note: for more information, see issue #124085 help: the value is now dropped here in Edition 2024 - --> $DIR/lint-if-let-rescope-with-macro.rs:13:38 + --> $DIR/lint-if-let-rescope-with-macro.rs:12:38 | LL | if let $p = $e { $($conseq)* } else { $($alt)* } | ^ @@ -29,7 +29,7 @@ LL | | {} LL | | }; | |_____- in this macro invocation note: the lint level is defined here - --> $DIR/lint-if-let-rescope-with-macro.rs:8:9 + --> $DIR/lint-if-let-rescope-with-macro.rs:7:9 | LL | #![deny(if_let_rescope)] | ^^^^^^^^^^^^^^ diff --git a/tests/ui/drop/lint-if-let-rescope.fixed b/tests/ui/drop/lint-if-let-rescope.fixed index 199068d0fd265..fec2e3b2ae705 100644 --- a/tests/ui/drop/lint-if-let-rescope.fixed +++ b/tests/ui/drop/lint-if-let-rescope.fixed @@ -1,7 +1,7 @@ //@ run-rustfix #![deny(if_let_rescope)] -#![feature(if_let_rescope, stmt_expr_attributes)] +#![feature(stmt_expr_attributes)] #![allow(irrefutable_let_patterns, unused_parens)] fn droppy() -> Droppy { diff --git a/tests/ui/drop/lint-if-let-rescope.rs b/tests/ui/drop/lint-if-let-rescope.rs index 4c043c0266cc4..ee184695b97ac 100644 --- a/tests/ui/drop/lint-if-let-rescope.rs +++ b/tests/ui/drop/lint-if-let-rescope.rs @@ -1,7 +1,7 @@ //@ run-rustfix #![deny(if_let_rescope)] -#![feature(if_let_rescope, stmt_expr_attributes)] +#![feature(stmt_expr_attributes)] #![allow(irrefutable_let_patterns, unused_parens)] fn droppy() -> Droppy { diff --git a/tests/ui/feature-gates/feature-gate-if-let-rescope.rs b/tests/ui/feature-gates/feature-gate-if-let-rescope.rs deleted file mode 100644 index bd1efd4fb7c1f..0000000000000 --- a/tests/ui/feature-gates/feature-gate-if-let-rescope.rs +++ /dev/null @@ -1,27 +0,0 @@ -// This test shows the code that could have been accepted by enabling #![feature(if_let_rescope)] - -struct A; -struct B<'a, T>(&'a mut T); - -impl A { - fn f(&mut self) -> Option> { - Some(B(self)) - } -} - -impl<'a, T> Drop for B<'a, T> { - fn drop(&mut self) { - // this is needed to keep NLL's hands off and to ensure - // the inner mutable borrow stays alive - } -} - -fn main() { - let mut a = A; - if let None = a.f().as_ref() { - unreachable!() - } else { - a.f().unwrap(); - //~^ ERROR cannot borrow `a` as mutable more than once at a time - }; -} diff --git a/tests/ui/feature-gates/feature-gate-if-let-rescope.stderr b/tests/ui/feature-gates/feature-gate-if-let-rescope.stderr deleted file mode 100644 index ff1846ae0b1f5..0000000000000 --- a/tests/ui/feature-gates/feature-gate-if-let-rescope.stderr +++ /dev/null @@ -1,18 +0,0 @@ -error[E0499]: cannot borrow `a` as mutable more than once at a time - --> $DIR/feature-gate-if-let-rescope.rs:24:9 - | -LL | if let None = a.f().as_ref() { - | ----- - | | - | first mutable borrow occurs here - | a temporary with access to the first borrow is created here ... -... -LL | a.f().unwrap(); - | ^ second mutable borrow occurs here -LL | -LL | }; - | - ... and the first borrow might be used here, when that temporary is dropped and runs the destructor for type `Option>` - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0499`. diff --git a/tests/ui/mir/mir_let_chains_drop_order.rs b/tests/ui/mir/mir_let_chains_drop_order.rs index daf0a62fc85f3..92199625207e9 100644 --- a/tests/ui/mir/mir_let_chains_drop_order.rs +++ b/tests/ui/mir/mir_let_chains_drop_order.rs @@ -8,7 +8,6 @@ // See `mir_drop_order.rs` for more information #![feature(let_chains)] -#![cfg_attr(edition2024, feature(if_let_rescope))] #![allow(irrefutable_let_patterns)] use std::cell::RefCell; diff --git a/tests/ui/nll/issue-54556-niconii.edition2021.stderr b/tests/ui/nll/issue-54556-niconii.edition2021.stderr index 31a03abbc9826..abee09ed95037 100644 --- a/tests/ui/nll/issue-54556-niconii.edition2021.stderr +++ b/tests/ui/nll/issue-54556-niconii.edition2021.stderr @@ -1,5 +1,5 @@ error[E0597]: `counter` does not live long enough - --> $DIR/issue-54556-niconii.rs:30:20 + --> $DIR/issue-54556-niconii.rs:28:20 | LL | let counter = Mutex; | ------- binding `counter` declared here diff --git a/tests/ui/nll/issue-54556-niconii.rs b/tests/ui/nll/issue-54556-niconii.rs index 1a7ad17cc84c0..f01e0523cbf9d 100644 --- a/tests/ui/nll/issue-54556-niconii.rs +++ b/tests/ui/nll/issue-54556-niconii.rs @@ -12,8 +12,6 @@ //@ [edition2024] compile-flags: -Z unstable-options //@ [edition2024] check-pass -#![cfg_attr(edition2024, feature(if_let_rescope))] - struct Mutex; struct MutexGuard<'a>(&'a Mutex); From 6ab87f82384d0265b486ba2aa41dcf942bd42c4f Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 26 Oct 2024 17:38:04 +0000 Subject: [PATCH 02/17] Collect item bounds for RPITITs from trait where clauses just like associated types --- .../src/collect/item_bounds.rs | 16 ++------------ .../implied-from-self-where-clause.rs | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 14 deletions(-) create mode 100644 tests/ui/associated-type-bounds/implied-from-self-where-clause.rs diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index b2ad42be6c7fc..5c4cecc02f0ee 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -367,20 +367,8 @@ pub(super) fn explicit_item_bounds_with_filter( // a projection self type. Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => { let opaque_ty = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_opaque_ty(); - let item_ty = Ty::new_projection_from_args( - tcx, - def_id.to_def_id(), - ty::GenericArgs::identity_for_item(tcx, def_id), - ); - let bounds = opaque_type_bounds( - tcx, - opaque_def_id.expect_local(), - opaque_ty.bounds, - item_ty, - opaque_ty.span, - filter, - ); - assert_only_contains_predicates_from(filter, bounds, item_ty); + let bounds = + associated_type_bounds(tcx, def_id, opaque_ty.bounds, opaque_ty.span, filter); return ty::EarlyBinder::bind(bounds); } Some(ty::ImplTraitInTraitData::Impl { .. }) => span_bug!( diff --git a/tests/ui/associated-type-bounds/implied-from-self-where-clause.rs b/tests/ui/associated-type-bounds/implied-from-self-where-clause.rs new file mode 100644 index 0000000000000..38f556969140a --- /dev/null +++ b/tests/ui/associated-type-bounds/implied-from-self-where-clause.rs @@ -0,0 +1,21 @@ +// Make sure that, like associated type where clauses on traits, we gather item +// bounds for RPITITs from RTN where clauses. + +//@ check-pass + +#![feature(return_type_notation)] + +trait Foo +where + Self::method(..): Send, +{ + fn method() -> impl Sized; +} + +fn is_send(_: impl Send) {} + +fn test() { + is_send(T::method()); +} + +fn main() {} From 42fbaf1ddde7c334ded228eff6e5fa31aff8fb94 Mon Sep 17 00:00:00 2001 From: Asuna Date: Wed, 9 Oct 2024 18:29:31 +0800 Subject: [PATCH 03/17] Add a new trait `proc_macro::ToTokens` --- library/proc_macro/src/lib.rs | 4 + library/proc_macro/src/to_tokens.rs | 310 ++++++++++++++++++++++++++++ 2 files changed, 314 insertions(+) create mode 100644 library/proc_macro/src/to_tokens.rs diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index ae47bb7adf49a..15770248b3106 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -32,6 +32,7 @@ #![feature(restricted_std)] #![feature(rustc_attrs)] #![feature(min_specialization)] +#![feature(extend_one)] #![recursion_limit = "256"] #![allow(internal_features)] #![deny(ffi_unwind_calls)] @@ -43,6 +44,7 @@ pub mod bridge; mod diagnostic; mod escape; +mod to_tokens; use std::ffi::CStr; use std::ops::{Range, RangeBounds}; @@ -52,6 +54,8 @@ use std::{error, fmt}; #[unstable(feature = "proc_macro_diagnostic", issue = "54140")] pub use diagnostic::{Diagnostic, Level, MultiSpan}; +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +pub use to_tokens::ToTokens; use crate::escape::{EscapeOptions, escape_bytes}; diff --git a/library/proc_macro/src/to_tokens.rs b/library/proc_macro/src/to_tokens.rs new file mode 100644 index 0000000000000..8f697b416d5c6 --- /dev/null +++ b/library/proc_macro/src/to_tokens.rs @@ -0,0 +1,310 @@ +use std::borrow::Cow; +use std::ffi::{CStr, CString}; +use std::rc::Rc; + +use crate::{ConcatTreesHelper, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; + +/// Types that can be interpolated inside a [`quote!`] invocation. +/// +/// [`quote!`]: crate::quote! +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +pub trait ToTokens { + /// Write `self` to the given `TokenStream`. + /// + /// # Example + /// + /// Example implementation for a struct representing Rust paths like + /// `std::cmp::PartialEq`: + /// + /// ``` + /// #![feature(proc_macro_totokens)] + /// + /// use std::iter; + /// use proc_macro::{Spacing, Punct, TokenStream, TokenTree, ToTokens}; + /// + /// pub struct Path { + /// pub global: bool, + /// pub segments: Vec, + /// } + /// + /// impl ToTokens for Path { + /// fn to_tokens(&self, tokens: &mut TokenStream) { + /// for (i, segment) in self.segments.iter().enumerate() { + /// if i > 0 || self.global { + /// // Double colon `::` + /// tokens.extend(iter::once(TokenTree::from(Punct::new(':', Spacing::Joint)))); + /// tokens.extend(iter::once(TokenTree::from(Punct::new(':', Spacing::Alone)))); + /// } + /// segment.to_tokens(tokens); + /// } + /// } + /// } + /// # + /// # pub struct PathSegment; + /// # + /// # impl ToTokens for PathSegment { + /// # fn to_tokens(&self, tokens: &mut TokenStream) { + /// # unimplemented!() + /// # } + /// # } + /// ``` + fn to_tokens(&self, tokens: &mut TokenStream); + + /// Convert `self` directly into a `TokenStream` object. + /// + /// This method is implicitly implemented using `to_tokens`, and acts as a + /// convenience method for consumers of the `ToTokens` trait. + fn to_token_stream(&self) -> TokenStream { + let mut tokens = TokenStream::new(); + self.to_tokens(&mut tokens); + tokens + } + + /// Convert `self` directly into a `TokenStream` object. + /// + /// This method is implicitly implemented using `to_tokens`, and acts as a + /// convenience method for consumers of the `ToTokens` trait. + fn into_token_stream(self) -> TokenStream + where + Self: Sized, + { + self.to_token_stream() + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for TokenTree { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(self.clone()); + } + + fn into_token_stream(self) -> TokenStream { + let mut builder = ConcatTreesHelper::new(1); + builder.push(self); + builder.build() + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for TokenStream { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend(self.clone()); + } + + fn into_token_stream(self) -> TokenStream { + self + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Literal { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Ident { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Punct { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Group { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend_one(TokenTree::from(self.clone())); + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for &T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for &mut T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Box { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Rc { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Cow<'_, T> { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for Option { + fn to_tokens(&self, tokens: &mut TokenStream) { + if let Some(t) = self { + t.to_tokens(tokens); + } + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u8 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u8_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u16 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u16_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u32_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u64_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for u128 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::u128_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i8 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i8_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i16 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i16_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i32_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i64_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for i128 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::i128_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for f32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::f32_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for f64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::f64_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for usize { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::usize_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for isize { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::isize_suffixed(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for bool { + fn to_tokens(&self, tokens: &mut TokenStream) { + let word = if *self { "true" } else { "false" }; + Ident::new(word, Span::call_site()).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for char { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::character(*self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for str { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::string(self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for String { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::string(self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for CStr { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::c_string(self).to_tokens(tokens) + } +} + +#[unstable(feature = "proc_macro_totokens", issue = "130977")] +impl ToTokens for CString { + fn to_tokens(&self, tokens: &mut TokenStream) { + Literal::c_string(self).to_tokens(tokens) + } +} From 4839d6e6e51f29c6bd9b581df520a8f1a6d278b9 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 27 Oct 2024 20:38:33 -0700 Subject: [PATCH 04/17] compiler: Add rustc_abi dependence to the compiler Depend on rustc_abi in compiler crates that use it indirectly but have not yet taken on that dependency, and are not entangled in my other PRs. This leaves an "excise rustc_target" step after the dust settles. --- Cargo.lock | 8 ++++++++ compiler/rustc_errors/Cargo.toml | 1 + compiler/rustc_errors/src/diagnostic_impls.rs | 2 +- compiler/rustc_hir_analysis/Cargo.toml | 1 + compiler/rustc_hir_analysis/src/check/check.rs | 2 +- compiler/rustc_hir_analysis/src/check/intrinsicck.rs | 2 +- compiler/rustc_hir_analysis/src/check/mod.rs | 2 +- compiler/rustc_metadata/Cargo.toml | 1 + compiler/rustc_metadata/src/rmeta/mod.rs | 2 +- compiler/rustc_mir_dataflow/Cargo.toml | 1 + compiler/rustc_mir_dataflow/src/drop_flag_effects.rs | 2 +- compiler/rustc_mir_dataflow/src/elaborate_drops.rs | 2 +- compiler/rustc_mir_dataflow/src/value_analysis.rs | 2 +- compiler/rustc_passes/Cargo.toml | 1 + compiler/rustc_passes/src/dead.rs | 2 +- compiler/rustc_passes/src/layout_test.rs | 2 +- compiler/rustc_pattern_analysis/Cargo.toml | 3 +++ compiler/rustc_pattern_analysis/src/rustc.rs | 2 +- compiler/rustc_pattern_analysis/src/rustc/print.rs | 2 +- compiler/rustc_session/Cargo.toml | 1 + compiler/rustc_session/src/code_stats.rs | 2 +- compiler/rustc_session/src/config/cfg.rs | 2 +- compiler/rustc_symbol_mangling/Cargo.toml | 2 ++ compiler/rustc_symbol_mangling/src/v0.rs | 2 +- 24 files changed, 34 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e814e7d7fdc..021cb3db56872 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3621,6 +3621,7 @@ version = "0.0.0" dependencies = [ "annotate-snippets 0.11.4", "derive_setters", + "rustc_abi", "rustc_ast", "rustc_ast_pretty", "rustc_data_structures", @@ -3718,6 +3719,7 @@ name = "rustc_hir_analysis" version = "0.0.0" dependencies = [ "itertools", + "rustc_abi", "rustc_arena", "rustc_ast", "rustc_attr", @@ -3980,6 +3982,7 @@ dependencies = [ "bitflags 2.6.0", "libloading", "odht", + "rustc_abi", "rustc_ast", "rustc_attr", "rustc_data_structures", @@ -4074,6 +4077,7 @@ version = "0.0.0" dependencies = [ "polonius-engine", "regex", + "rustc_abi", "rustc_ast", "rustc_data_structures", "rustc_errors", @@ -4187,6 +4191,7 @@ dependencies = [ name = "rustc_passes" version = "0.0.0" dependencies = [ + "rustc_abi", "rustc_ast", "rustc_ast_pretty", "rustc_attr", @@ -4213,6 +4218,7 @@ name = "rustc_pattern_analysis" version = "0.0.0" dependencies = [ "rustc-hash 2.0.0", + "rustc_abi", "rustc_apfloat", "rustc_arena", "rustc_data_structures", @@ -4352,6 +4358,7 @@ dependencies = [ "bitflags 2.6.0", "getopts", "libc", + "rustc_abi", "rustc_ast", "rustc_data_structures", "rustc_errors", @@ -4415,6 +4422,7 @@ version = "0.0.0" dependencies = [ "punycode", "rustc-demangle", + "rustc_abi", "rustc_data_structures", "rustc_errors", "rustc_hir", diff --git a/compiler/rustc_errors/Cargo.toml b/compiler/rustc_errors/Cargo.toml index 00eaf4d5a862d..41ebe4ae26737 100644 --- a/compiler/rustc_errors/Cargo.toml +++ b/compiler/rustc_errors/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" # tidy-alphabetical-start annotate-snippets = "0.11" derive_setters = "0.1.6" +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index 19529f06ef1d2..09a608dda7ba2 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -5,12 +5,12 @@ use std::num::ParseIntError; use std::path::{Path, PathBuf}; use std::process::ExitStatus; +use rustc_abi::TargetDataLayoutErrors; use rustc_ast_pretty::pprust; use rustc_macros::Subdiagnostic; use rustc_span::Span; use rustc_span::edition::Edition; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol}; -use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple}; use rustc_type_ir::{ClosureKind, FloatTy}; use {rustc_ast as ast, rustc_hir as hir}; diff --git a/compiler/rustc_hir_analysis/Cargo.toml b/compiler/rustc_hir_analysis/Cargo.toml index 04ca7f123d3e0..3c8887f08bc85 100644 --- a/compiler/rustc_hir_analysis/Cargo.toml +++ b/compiler/rustc_hir_analysis/Cargo.toml @@ -10,6 +10,7 @@ doctest = false [dependencies] # tidy-alphabetical-start itertools = "0.12" +rustc_abi = { path = "../rustc_abi" } rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 97f3f1c8ef27b..95c902946c3a9 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -1,6 +1,7 @@ use std::cell::LazyCell; use std::ops::ControlFlow; +use rustc_abi::FieldIdx; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::MultiSpan; use rustc_errors::codes::*; @@ -23,7 +24,6 @@ use rustc_middle::ty::{ TypeVisitableExt, }; use rustc_session::lint::builtin::UNINHABITED_STATIC; -use rustc_target::abi::FieldIdx; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective; use rustc_trait_selection::traits; diff --git a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index bbff00cd3b3c2..e95669c9d4090 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -1,5 +1,6 @@ use std::assert_matches::debug_assert_matches; +use rustc_abi::FieldIdx; use rustc_ast::InlineAsmTemplatePiece; use rustc_data_structures::fx::FxIndexSet; use rustc_hir::{self as hir, LangItem}; @@ -8,7 +9,6 @@ use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, TypeVisitableExt, UintT use rustc_session::lint; use rustc_span::Symbol; use rustc_span::def_id::LocalDefId; -use rustc_target::abi::FieldIdx; use rustc_target::asm::{ InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmType, ModifierInfo, }; diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index f2f9c69e49f70..b15243d419ec0 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -74,6 +74,7 @@ pub mod wfcheck; use std::num::NonZero; pub use check::{check_abi, check_abi_fn_ptr}; +use rustc_abi::VariantIdx; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::{Diag, ErrorGuaranteed, pluralize, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -90,7 +91,6 @@ use rustc_session::parse::feature_err; use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{BytePos, DUMMY_SP, Span, Symbol}; -use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::infer::ObligationCauseExt as _; diff --git a/compiler/rustc_metadata/Cargo.toml b/compiler/rustc_metadata/Cargo.toml index 79d3482472a81..3b0151b1f9444 100644 --- a/compiler/rustc_metadata/Cargo.toml +++ b/compiler/rustc_metadata/Cargo.toml @@ -8,6 +8,7 @@ edition = "2021" bitflags = "2.4.1" libloading = "0.8.0" odht = { version = "0.3.1", features = ["nightly"] } +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index a00ca27aacc0c..f1844045677ed 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -6,6 +6,7 @@ use decoder::{DecodeContext, Metadata}; use def_path_hash_map::DefPathHashMapRef; use encoder::EncodeContext; pub use encoder::{EncodedMetadata, encode_metadata, rendered_const}; +use rustc_abi::{FieldIdx, VariantIdx}; use rustc_ast::expand::StrippedCfgItem; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::svh::Svh; @@ -37,7 +38,6 @@ use rustc_span::edition::Edition; use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextData}; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span}; -use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_target::spec::{PanicStrategy, TargetTriple}; use table::TableBuilder; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; diff --git a/compiler/rustc_mir_dataflow/Cargo.toml b/compiler/rustc_mir_dataflow/Cargo.toml index 7199db677c464..62a69b3464f0d 100644 --- a/compiler/rustc_mir_dataflow/Cargo.toml +++ b/compiler/rustc_mir_dataflow/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" # tidy-alphabetical-start polonius-engine = "0.13.0" regex = "1" +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs index bb53eaf6cbd1c..e5cddd0e5e4b7 100644 --- a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs +++ b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs @@ -1,5 +1,5 @@ +use rustc_abi::VariantIdx; use rustc_middle::mir::{self, Body, Location, Terminator, TerminatorKind}; -use rustc_target::abi::VariantIdx; use tracing::debug; use super::move_paths::{InitKind, LookupResult, MoveData, MovePathIndex}; diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index 7f2a07e2f5e0f..9a1f000d39d88 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -1,5 +1,6 @@ use std::{fmt, iter}; +use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use rustc_hir::lang_items::LangItem; use rustc_index::Idx; use rustc_middle::mir::patch::MirPatch; @@ -10,7 +11,6 @@ use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; use rustc_span::DUMMY_SP; use rustc_span::source_map::Spanned; -use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use tracing::{debug, instrument}; /// The value of an inserted drop flag. diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index d0f62bd82d17d..f7d4a082779b7 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -36,6 +36,7 @@ use std::assert_matches::assert_matches; use std::fmt::{Debug, Formatter}; use std::ops::Range; +use rustc_abi::{FieldIdx, VariantIdx}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry}; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -46,7 +47,6 @@ use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_target::abi::{FieldIdx, VariantIdx}; use tracing::debug; use crate::fmt::DebugWithContext; diff --git a/compiler/rustc_passes/Cargo.toml b/compiler/rustc_passes/Cargo.toml index b45a8dae277ed..ed5991459ac1b 100644 --- a/compiler/rustc_passes/Cargo.toml +++ b/compiler/rustc_passes/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index af17fbf7e4df3..b1db66fa52d4b 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -7,6 +7,7 @@ use std::mem; use hir::ItemKind; use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; +use rustc_abi::FieldIdx; use rustc_data_structures::unord::UnordSet; use rustc_errors::MultiSpan; use rustc_hir as hir; @@ -22,7 +23,6 @@ use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_session::lint::builtin::DEAD_CODE; use rustc_span::symbol::{Symbol, sym}; -use rustc_target::abi::FieldIdx; use crate::errors::{ ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment, diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 93729a7f6df8c..0b6cf82ca8b46 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -1,3 +1,4 @@ +use rustc_abi::{HasDataLayout, TargetDataLayout}; use rustc_ast::Attribute; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; @@ -7,7 +8,6 @@ use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt}; use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_target::abi::{HasDataLayout, TargetDataLayout}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::TyCtxtInferExt; use rustc_trait_selection::traits; diff --git a/compiler/rustc_pattern_analysis/Cargo.toml b/compiler/rustc_pattern_analysis/Cargo.toml index 34fb1bdf6fa79..f98e4243375f2 100644 --- a/compiler/rustc_pattern_analysis/Cargo.toml +++ b/compiler/rustc_pattern_analysis/Cargo.toml @@ -6,6 +6,8 @@ edition = "2021" [dependencies] # tidy-alphabetical-start rustc-hash = "2.0.0" + +rustc_abi = { path = "../rustc_abi", optional = true } rustc_apfloat = "0.2.0" rustc_arena = { path = "../rustc_arena", optional = true } rustc_data_structures = { path = "../rustc_data_structures", optional = true } @@ -29,6 +31,7 @@ tracing-tree = "0.3.0" [features] default = ["rustc"] rustc = [ + "dep:rustc_abi", "dep:rustc_arena", "dep:rustc_data_structures", "dep:rustc_errors", diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 0e132b27fb4cd..9ea5023064c1c 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -1,6 +1,7 @@ use std::fmt; use std::iter::once; +use rustc_abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx}; use rustc_arena::DroplessArena; use rustc_hir::HirId; use rustc_hir::def_id::DefId; @@ -15,7 +16,6 @@ use rustc_middle::ty::{ use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; -use rustc_target::abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx}; use crate::constructor::Constructor::*; use crate::constructor::{ diff --git a/compiler/rustc_pattern_analysis/src/rustc/print.rs b/compiler/rustc_pattern_analysis/src/rustc/print.rs index 17e389df17ed2..7649f72f8681b 100644 --- a/compiler/rustc_pattern_analysis/src/rustc/print.rs +++ b/compiler/rustc_pattern_analysis/src/rustc/print.rs @@ -11,10 +11,10 @@ use std::fmt; +use rustc_abi::{FieldIdx, VariantIdx}; use rustc_middle::bug; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt}; use rustc_span::sym; -use rustc_target::abi::{FieldIdx, VariantIdx}; #[derive(Clone, Debug)] pub(crate) struct FieldPat { diff --git a/compiler/rustc_session/Cargo.toml b/compiler/rustc_session/Cargo.toml index 75cc8f18a5455..e9983699609da 100644 --- a/compiler/rustc_session/Cargo.toml +++ b/compiler/rustc_session/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" # tidy-alphabetical-start bitflags = "2.4.1" getopts = "0.2" +rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_session/src/code_stats.rs b/compiler/rustc_session/src/code_stats.rs index 7a32c0c26555e..f3c21992784c0 100644 --- a/compiler/rustc_session/src/code_stats.rs +++ b/compiler/rustc_session/src/code_stats.rs @@ -1,10 +1,10 @@ use std::cmp; +use rustc_abi::{Align, Size}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lock; use rustc_span::Symbol; use rustc_span::def_id::DefId; -use rustc_target::abi::{Align, Size}; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct VariantInfo { diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index ccc01728958b8..31ef2bda4f1e5 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -23,12 +23,12 @@ use std::hash::Hash; use std::iter; +use rustc_abi::Align; use rustc_ast::ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_lint_defs::BuiltinLintDiag; use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS; use rustc_span::symbol::{Symbol, sym}; -use rustc_target::abi::Align; use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, TARGETS, Target, TargetTriple}; use crate::Session; diff --git a/compiler/rustc_symbol_mangling/Cargo.toml b/compiler/rustc_symbol_mangling/Cargo.toml index 65aa9e40c8ba3..644e710d1db84 100644 --- a/compiler/rustc_symbol_mangling/Cargo.toml +++ b/compiler/rustc_symbol_mangling/Cargo.toml @@ -7,6 +7,8 @@ edition = "2021" # tidy-alphabetical-start punycode = "0.4.0" rustc-demangle = "0.1.21" + +rustc_abi = { path = "../rustc_abi" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_hir = { path = "../rustc_hir" } diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index d092fa8f0820f..868345c75945f 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -2,6 +2,7 @@ use std::fmt::Write; use std::iter; use std::ops::Range; +use rustc_abi::Integer; use rustc_data_structures::base_n::ToBaseN; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; @@ -17,7 +18,6 @@ use rustc_middle::ty::{ TyCtxt, TypeVisitable, TypeVisitableExt, UintTy, }; use rustc_span::symbol::kw; -use rustc_target::abi::Integer; use rustc_target::spec::abi::Abi; pub(super) fn mangle<'tcx>( From cb08e087221ba0263a338e959264520a8ed8080e Mon Sep 17 00:00:00 2001 From: Adwin White Date: Thu, 12 Sep 2024 11:32:39 +0800 Subject: [PATCH 05/17] Lower AST node id only once --- compiler/rustc_ast_lowering/src/block.rs | 14 ++- compiler/rustc_ast_lowering/src/delegation.rs | 5 +- compiler/rustc_ast_lowering/src/expr.rs | 113 +++++++++++------- compiler/rustc_ast_lowering/src/item.rs | 14 ++- compiler/rustc_ast_lowering/src/lib.rs | 65 +++++----- compiler/rustc_ast_lowering/src/pat.rs | 58 ++++++--- tests/ui/thir-print/thir-tree-match.stdout | 46 +++---- 7 files changed, 184 insertions(+), 131 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/block.rs b/compiler/rustc_ast_lowering/src/block.rs index 9d2b5690c23d9..8e02cbfd2ca81 100644 --- a/compiler/rustc_ast_lowering/src/block.rs +++ b/compiler/rustc_ast_lowering/src/block.rs @@ -10,17 +10,27 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { b: &Block, targeted_by_break: bool, ) -> &'hir hir::Block<'hir> { - self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break)) + let hir_id = self.lower_node_id(b.id); + self.arena.alloc(self.lower_block_noalloc(hir_id, b, targeted_by_break)) + } + + pub(super) fn lower_block_with_hir_id( + &mut self, + b: &Block, + hir_id: hir::HirId, + targeted_by_break: bool, + ) -> &'hir hir::Block<'hir> { + self.arena.alloc(self.lower_block_noalloc(hir_id, b, targeted_by_break)) } pub(super) fn lower_block_noalloc( &mut self, + hir_id: hir::HirId, b: &Block, targeted_by_break: bool, ) -> hir::Block<'hir> { let (stmts, expr) = self.lower_stmts(&b.stmts); let rules = self.lower_block_check_mode(&b.rules); - let hir_id = self.lower_node_id(b.id); hir::Block { hir_id, stmts, expr, rules, span: self.lower_span(b.span), targeted_by_break } } diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 3b85f1737bdd9..37eea707929e7 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -259,10 +259,11 @@ impl<'hir> LoweringContext<'_, 'hir> { self_param_id: pat_node_id, }; self_resolver.visit_block(block); + // Target expr needs to lower `self` path. + this.ident_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id); this.lower_target_expr(&block) } else { - let pat_hir_id = this.lower_node_id(pat_node_id); - this.generate_arg(pat_hir_id, span) + this.generate_arg(param.pat.hir_id, span) }; args.push(arg); } diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index a1a16d0ca2632..3df945a18e80a 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -70,8 +70,8 @@ impl<'hir> LoweringContext<'_, 'hir> { _ => (), } - let hir_id = self.lower_node_id(e.id); - self.lower_attrs(hir_id, &e.attrs); + let expr_hir_id = self.lower_node_id(e.id); + self.lower_attrs(expr_hir_id, &e.attrs); let kind = match &e.kind { ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), @@ -175,18 +175,25 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::If(cond, then, else_opt) => { self.lower_expr_if(cond, then, else_opt.as_deref()) } - ExprKind::While(cond, body, opt_label) => self.with_loop_scope(e.id, |this| { - let span = this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None); - this.lower_expr_while_in_loop_scope(span, cond, body, *opt_label) - }), - ExprKind::Loop(body, opt_label, span) => self.with_loop_scope(e.id, |this| { - hir::ExprKind::Loop( - this.lower_block(body, false), - this.lower_label(*opt_label), - hir::LoopSource::Loop, - this.lower_span(*span), - ) - }), + ExprKind::While(cond, body, opt_label) => { + self.with_loop_scope(expr_hir_id, |this| { + let span = + this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None); + let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id); + this.lower_expr_while_in_loop_scope(span, cond, body, opt_label) + }) + } + ExprKind::Loop(body, opt_label, span) => { + self.with_loop_scope(expr_hir_id, |this| { + let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id); + hir::ExprKind::Loop( + this.lower_block(body, false), + opt_label, + hir::LoopSource::Loop, + this.lower_span(*span), + ) + }) + } ExprKind::TryBlock(body) => self.lower_expr_try_block(body), ExprKind::Match(expr, arms, kind) => hir::ExprKind::Match( self.lower_expr(expr), @@ -212,7 +219,7 @@ impl<'hir> LoweringContext<'_, 'hir> { binder, *capture_clause, e.id, - hir_id, + expr_hir_id, *coroutine_kind, fn_decl, body, @@ -223,7 +230,7 @@ impl<'hir> LoweringContext<'_, 'hir> { binder, *capture_clause, e.id, - hir_id, + expr_hir_id, *constness, *movability, fn_decl, @@ -250,8 +257,14 @@ impl<'hir> LoweringContext<'_, 'hir> { ) } ExprKind::Block(blk, opt_label) => { - let opt_label = self.lower_label(*opt_label); - hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label) + // Different from loops, label of block resolves to block id rather than + // expr node id. + let block_hir_id = self.lower_node_id(blk.id); + let opt_label = self.lower_label(*opt_label, blk.id, block_hir_id); + hir::ExprKind::Block( + self.lower_block_with_hir_id(blk, block_hir_id, opt_label.is_some()), + opt_label, + ) } ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span), ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp( @@ -354,7 +367,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span), }; - hir::Expr { hir_id, kind, span: self.lower_span(e.span) } + hir::Expr { hir_id: expr_hir_id, kind, span: self.lower_span(e.span) } }) } @@ -504,7 +517,6 @@ impl<'hir> LoweringContext<'_, 'hir> { let if_expr = self.expr(span, if_kind); let block = self.block_expr(self.arena.alloc(if_expr)); let span = self.lower_span(span.with_hi(cond.span.hi())); - let opt_label = self.lower_label(opt_label); hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span) } @@ -512,8 +524,9 @@ impl<'hir> LoweringContext<'_, 'hir> { /// `try { ; }` into `{ ; ::std::ops::Try::from_output(()) }` /// and save the block id to use it as a break target for desugaring of the `?` operator. fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> { - self.with_catch_scope(body.id, |this| { - let mut block = this.lower_block_noalloc(body, true); + let body_hir_id = self.lower_node_id(body.id); + self.with_catch_scope(body_hir_id, |this| { + let mut block = this.lower_block_noalloc(body_hir_id, body, true); // Final expression of the block (if present) or `()` with span at the end of block let (try_span, tail_expr) = if let Some(expr) = block.expr.take() { @@ -869,7 +882,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid); let ready_field = self.single_pat_field(gen_future_span, x_pat); let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field); - let break_x = self.with_loop_scope(loop_node_id, move |this| { + let break_x = self.with_loop_scope(loop_hir_id, move |this| { let expr_break = hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr)); this.arena.alloc(this.expr(gen_future_span, expr_break)) @@ -1101,8 +1114,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::CoroutineSource::Closure, ); - let hir_id = this.lower_node_id(coroutine_kind.closure_id()); - this.maybe_forward_track_caller(body.span, closure_hir_id, hir_id); + this.maybe_forward_track_caller(body.span, closure_hir_id, expr.hir_id); (parameters, expr) }); @@ -1465,8 +1477,16 @@ impl<'hir> LoweringContext<'_, 'hir> { ) } - fn lower_label(&self, opt_label: Option