Skip to content

Reduce ast::ptr::P to a typedef of Box #141603

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1123,10 +1123,9 @@ impl Stmt {
pub fn add_trailing_semicolon(mut self) -> Self {
self.kind = match self.kind {
StmtKind::Expr(expr) => StmtKind::Semi(expr),
StmtKind::MacCall(mac) => {
StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
}))
StmtKind::MacCall(mut mac) => {
mac.style = MacStmtStyle::Semicolon;
StmtKind::MacCall(mac)
}
kind => kind,
};
Expand Down Expand Up @@ -1715,7 +1714,7 @@ pub enum ExprKind {
///
/// Usually not written directly in user code but
/// indirectly via the macro `core::mem::offset_of!(...)`.
OffsetOf(P<Ty>, P<[Ident]>),
OffsetOf(P<Ty>, Vec<Ident>),

/// A macro invocation; pre-expansion.
MacCall(P<MacCall>),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_ast/src/attr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl Attribute {

pub fn unwrap_normal_item(self) -> AttrItem {
match self.kind {
AttrKind::Normal(normal) => normal.into_inner().item,
AttrKind::Normal(normal) => normal.item,
AttrKind::DocComment(..) => panic!("unexpected doc comment"),
}
}
Expand Down
210 changes: 6 additions & 204 deletions compiler/rustc_ast/src/ptr.rs
Original file line number Diff line number Diff line change
@@ -1,209 +1,11 @@
//! The AST pointer.
//!
//! Provides [`P<T>`][struct@P], an owned smart pointer.
//!
//! # Motivations and benefits
//!
//! * **Identity**: sharing AST nodes is problematic for the various analysis
//! passes (e.g., one may be able to bypass the borrow checker with a shared
//! `ExprKind::AddrOf` node taking a mutable borrow).
//!
//! * **Efficiency**: folding can reuse allocation space for `P<T>` and `Vec<T>`,
//! the latter even when the input and output types differ (as it would be the
//! case with arenas or a GADT AST using type parameters to toggle features).
//!
//! * **Maintainability**: `P<T>` provides an interface, which can remain fully
//! functional even if the implementation changes (using a special thread-local
//! heap, for example). Moreover, a switch to, e.g., `P<'a, T>` would be easy
//! and mostly automated.

use std::fmt::{self, Debug, Display};
use std::ops::{Deref, DerefMut};
use std::{slice, vec};

use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
/// An owned smart pointer.
/// A pointer type that uniquely owns a heap allocation of type T.
///
/// See the [module level documentation][crate::ptr] for details.
pub struct P<T: ?Sized> {
ptr: Box<T>,
}
/// This used to be its own type, but now it's just a typedef for `Box` and we are planning to
/// remove it soon.
pub type P<T> = Box<T>;

/// Construct a `P<T>` from a `T` value.
#[allow(non_snake_case)]
pub fn P<T: 'static>(value: T) -> P<T> {
P { ptr: Box::new(value) }
}

impl<T: 'static> P<T> {
/// Move out of the pointer.
/// Intended for chaining transformations not covered by `map`.
pub fn and_then<U, F>(self, f: F) -> U
where
F: FnOnce(T) -> U,
{
f(*self.ptr)
}

/// Equivalent to `and_then(|x| x)`.
pub fn into_inner(self) -> T {
*self.ptr
}

/// Produce a new `P<T>` from `self` without reallocating.
pub fn map<F>(mut self, f: F) -> P<T>
where
F: FnOnce(T) -> T,
{
let x = f(*self.ptr);
*self.ptr = x;

self
}

/// Optionally produce a new `P<T>` from `self` without reallocating.
pub fn filter_map<F>(mut self, f: F) -> Option<P<T>>
where
F: FnOnce(T) -> Option<T>,
{
*self.ptr = f(*self.ptr)?;
Some(self)
}
}

impl<T: ?Sized> Deref for P<T> {
type Target = T;

fn deref(&self) -> &T {
&self.ptr
}
}

impl<T: ?Sized> DerefMut for P<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.ptr
}
}

impl<T: 'static + Clone> Clone for P<T> {
fn clone(&self) -> P<T> {
P((**self).clone())
}
}

impl<T: ?Sized + Debug> Debug for P<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(&self.ptr, f)
}
}

impl<T: Display> Display for P<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&**self, f)
}
}

impl<T> fmt::Pointer for P<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&self.ptr, f)
}
}

impl<D: Decoder, T: 'static + Decodable<D>> Decodable<D> for P<T> {
fn decode(d: &mut D) -> P<T> {
P(Decodable::decode(d))
}
}

impl<S: Encoder, T: Encodable<S>> Encodable<S> for P<T> {
fn encode(&self, s: &mut S) {
(**self).encode(s);
}
}

impl<T> P<[T]> {
// FIXME(const-hack) make this const again
pub fn new() -> P<[T]> {
P { ptr: Box::default() }
}

#[inline(never)]
pub fn from_vec(v: Vec<T>) -> P<[T]> {
P { ptr: v.into_boxed_slice() }
}

#[inline(never)]
pub fn into_vec(self) -> Vec<T> {
self.ptr.into_vec()
}
}

impl<T> Default for P<[T]> {
/// Creates an empty `P<[T]>`.
fn default() -> P<[T]> {
P::new()
}
}

impl<T: Clone> Clone for P<[T]> {
fn clone(&self) -> P<[T]> {
P::from_vec(self.to_vec())
}
}

impl<T> From<Vec<T>> for P<[T]> {
fn from(v: Vec<T>) -> Self {
P::from_vec(v)
}
}

impl<T> From<P<[T]>> for Vec<T> {
fn from(val: P<[T]>) -> Self {
val.into_vec()
}
}

impl<T> FromIterator<T> for P<[T]> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> P<[T]> {
P::from_vec(iter.into_iter().collect())
}
}

impl<T> IntoIterator for P<[T]> {
type Item = T;
type IntoIter = vec::IntoIter<T>;

fn into_iter(self) -> Self::IntoIter {
self.into_vec().into_iter()
}
}

impl<'a, T> IntoIterator for &'a P<[T]> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.ptr.iter()
}
}

impl<S: Encoder, T: Encodable<S>> Encodable<S> for P<[T]> {
fn encode(&self, s: &mut S) {
Encodable::encode(&**self, s);
}
}

impl<D: Decoder, T: Decodable<D>> Decodable<D> for P<[T]> {
fn decode(d: &mut D) -> P<[T]> {
P::from_vec(Decodable::decode(d))
}
}

impl<CTX, T> HashStable<CTX> for P<T>
where
T: ?Sized + HashStable<CTX>,
{
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
(**self).hash_stable(hcx, hasher);
}
pub fn P<T>(value: T) -> P<T> {
Box::new(value)
}
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/deriving/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl MultiItemModifier for BuiltinDerive {
let mut items = Vec::new();
match item {
Annotatable::Stmt(stmt) => {
if let ast::StmtKind::Item(item) = stmt.into_inner().kind {
if let ast::StmtKind::Item(item) = stmt.kind {
(self.0)(
ecx,
span,
Expand Down
20 changes: 9 additions & 11 deletions compiler/rustc_builtin_macros/src/pattern_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,12 @@ fn parse_pat_ty<'a>(cx: &mut ExtCtxt<'a>, stream: TokenStream) -> PResult<'a, (P

let pat = pat_to_ty_pat(
cx,
parser
.parse_pat_no_top_guard(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::EitherTupleOrPipe,
)?
.into_inner(),
*parser.parse_pat_no_top_guard(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::EitherTupleOrPipe,
)?,
);

if parser.token != token::Eof {
Expand All @@ -58,9 +56,9 @@ fn pat_to_ty_pat(cx: &mut ExtCtxt<'_>, pat: ast::Pat) -> P<TyPat> {
end.map(|value| P(AnonConst { id: DUMMY_NODE_ID, value })),
include_end,
),
ast::PatKind::Or(variants) => TyPatKind::Or(
variants.into_iter().map(|pat| pat_to_ty_pat(cx, pat.into_inner())).collect(),
),
ast::PatKind::Or(variants) => {
TyPatKind::Or(variants.into_iter().map(|pat| pat_to_ty_pat(cx, *pat)).collect())
}
ast::PatKind::Err(guar) => TyPatKind::Err(guar),
_ => TyPatKind::Err(cx.dcx().span_err(pat.span, "pattern not supported in pattern types")),
};
Expand Down
36 changes: 17 additions & 19 deletions compiler/rustc_builtin_macros/src/proc_macro_harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,30 +354,28 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
})
.collect();

let decls_static = cx
.item_static(
let mut decls_static = cx.item_static(
span,
Ident::new(sym::_DECLS, span),
cx.ty_ref(
span,
Ident::new(sym::_DECLS, span),
cx.ty_ref(
cx.ty(
span,
cx.ty(
span,
ast::TyKind::Slice(
cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
),
ast::TyKind::Slice(
cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
),
None,
ast::Mutability::Not,
),
None,
ast::Mutability::Not,
cx.expr_array_ref(span, decls),
)
.map(|mut i| {
i.attrs.push(cx.attr_word(sym::rustc_proc_macro_decls, span));
i.attrs.push(cx.attr_word(sym::used, span));
i.attrs.push(cx.attr_nested_word(sym::allow, sym::deprecated, span));
i
});
),
ast::Mutability::Not,
cx.expr_array_ref(span, decls),
);
decls_static.attrs.extend([
cx.attr_word(sym::rustc_proc_macro_decls, span),
cx.attr_word(sym::used, span),
cx.attr_nested_word(sym::allow, sym::deprecated, span),
]);

let block = cx.expr_block(
cx.block(span, thin_vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]),
Expand Down
13 changes: 3 additions & 10 deletions compiler/rustc_builtin_macros/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub(crate) fn expand_test_case(
let (mut item, is_stmt) = match anno_item {
Annotatable::Item(item) => (item, false),
Annotatable::Stmt(stmt) if let ast::StmtKind::Item(_) = stmt.kind => {
if let ast::StmtKind::Item(i) = stmt.into_inner().kind {
if let ast::StmtKind::Item(i) = stmt.kind {
(i, true)
} else {
unreachable!()
Expand Down Expand Up @@ -120,11 +120,7 @@ pub(crate) fn expand_test_or_bench(
Annotatable::Item(i) => (i, false),
Annotatable::Stmt(stmt) if matches!(stmt.kind, ast::StmtKind::Item(_)) => {
// FIXME: Use an 'if let' guard once they are implemented
if let ast::StmtKind::Item(i) = stmt.into_inner().kind {
(i, true)
} else {
unreachable!()
}
if let ast::StmtKind::Item(i) = stmt.kind { (i, true) } else { unreachable!() }
Comment on lines 122 to +123
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be fixed. I'll do so in a followup.

}
other => {
not_testable_error(cx, attr_sp, None);
Expand Down Expand Up @@ -381,10 +377,7 @@ pub(crate) fn expand_test_or_bench(
.into(),
),
);
test_const = test_const.map(|mut tc| {
tc.vis.kind = ast::VisibilityKind::Public;
tc
});
test_const.vis.kind = ast::VisibilityKind::Public;

// extern crate test
let test_extern =
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ impl Annotatable {

pub fn expect_stmt(self) -> ast::Stmt {
match self {
Annotatable::Stmt(stmt) => stmt.into_inner(),
Annotatable::Stmt(stmt) => *stmt,
_ => panic!("expected statement"),
}
}
Expand Down
Loading
Loading