Skip to content

Commit fb691b4

Browse files
authored
Rollup merge of #130635 - eholk:pin-reborrow-sugar, r=compiler-errors
Add `&pin (mut|const) T` type position sugar This adds parser support for `&pin mut T` and `&pin const T` references. These are desugared to `Pin<&mut T>` and `Pin<&T>` in the AST lowering phases. This PR currently includes #130526 since that one is in the commit queue. Only the most recent commits (bd45002 and following) are new. Tracking: - #130494 r? `@compiler-errors`
2 parents 3a00d35 + 3aabe1e commit fb691b4

File tree

25 files changed

+286
-39
lines changed

25 files changed

+286
-39
lines changed

compiler/rustc_ast/src/ast.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use std::{cmp, fmt, mem};
2323

2424
pub use GenericArgs::*;
2525
pub use UnsafeSource::*;
26-
pub use rustc_ast_ir::{Movability, Mutability};
26+
pub use rustc_ast_ir::{Movability, Mutability, Pinnedness};
2727
use rustc_data_structures::packed::Pu128;
2828
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
2929
use rustc_data_structures::stack::ensure_sufficient_stack;
@@ -2161,6 +2161,10 @@ pub enum TyKind {
21612161
Ptr(MutTy),
21622162
/// A reference (`&'a T` or `&'a mut T`).
21632163
Ref(Option<Lifetime>, MutTy),
2164+
/// A pinned reference (`&'a pin const T` or `&'a pin mut T`).
2165+
///
2166+
/// Desugars into `Pin<&'a T>` or `Pin<&'a mut T>`.
2167+
PinnedRef(Option<Lifetime>, MutTy),
21642168
/// A bare function (e.g., `fn(usize) -> bool`).
21652169
BareFn(P<BareFnTy>),
21662170
/// The never type (`!`).
@@ -2501,7 +2505,10 @@ impl Param {
25012505
if ident.name == kw::SelfLower {
25022506
return match self.ty.kind {
25032507
TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2504-
TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2508+
TyKind::Ref(lt, MutTy { ref ty, mutbl })
2509+
| TyKind::PinnedRef(lt, MutTy { ref ty, mutbl })
2510+
if ty.kind.is_implicit_self() =>
2511+
{
25052512
Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
25062513
}
25072514
_ => Some(respan(

compiler/rustc_ast/src/mut_visit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,7 @@ pub fn walk_ty<T: MutVisitor>(vis: &mut T, ty: &mut P<Ty>) {
485485
}
486486
TyKind::Slice(ty) => vis.visit_ty(ty),
487487
TyKind::Ptr(mt) => vis.visit_mt(mt),
488-
TyKind::Ref(lt, mt) => {
488+
TyKind::Ref(lt, mt) | TyKind::PinnedRef(lt, mt) => {
489489
visit_opt(lt, |lt| vis.visit_lifetime(lt));
490490
vis.visit_mt(mt);
491491
}

compiler/rustc_ast/src/util/classify.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,9 @@ fn type_trailing_braced_mac_call(mut ty: &ast::Ty) -> Option<&ast::MacCall> {
247247
break (mac.args.delim == Delimiter::Brace).then_some(mac);
248248
}
249249

250-
ast::TyKind::Ptr(mut_ty) | ast::TyKind::Ref(_, mut_ty) => {
250+
ast::TyKind::Ptr(mut_ty)
251+
| ast::TyKind::Ref(_, mut_ty)
252+
| ast::TyKind::PinnedRef(_, mut_ty) => {
251253
ty = &mut_ty.ty;
252254
}
253255

compiler/rustc_ast/src/visit.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,8 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) -> V::Result {
499499
match kind {
500500
TyKind::Slice(ty) | TyKind::Paren(ty) => try_visit!(visitor.visit_ty(ty)),
501501
TyKind::Ptr(MutTy { ty, mutbl: _ }) => try_visit!(visitor.visit_ty(ty)),
502-
TyKind::Ref(opt_lifetime, MutTy { ty, mutbl: _ }) => {
502+
TyKind::Ref(opt_lifetime, MutTy { ty, mutbl: _ })
503+
| TyKind::PinnedRef(opt_lifetime, MutTy { ty, mutbl: _ }) => {
503504
visit_opt!(visitor, visit_lifetime, opt_lifetime, LifetimeCtxt::Ref);
504505
try_visit!(visitor.visit_ty(ty));
505506
}

compiler/rustc_ast_ir/src/lib.rs

+7
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,10 @@ impl Mutability {
7979
matches!(self, Self::Not)
8080
}
8181
}
82+
83+
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
84+
#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))]
85+
pub enum Pinnedness {
86+
Not,
87+
Pinned,
88+
}

compiler/rustc_ast_lowering/src/expr.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
640640
self.lower_span(span),
641641
Some(self.allow_gen_future.clone()),
642642
);
643-
let resume_ty = self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span);
643+
let resume_ty =
644+
self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span, None);
644645
let input_ty = hir::Ty {
645646
hir_id: self.next_id(),
646647
kind: hir::TyKind::Path(resume_ty),
@@ -2065,7 +2066,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
20652066
lang_item: hir::LangItem,
20662067
name: Symbol,
20672068
) -> hir::Expr<'hir> {
2068-
let qpath = self.make_lang_item_qpath(lang_item, self.lower_span(span));
2069+
let qpath = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
20692070
let path = hir::ExprKind::Path(hir::QPath::TypeRelative(
20702071
self.arena.alloc(self.ty(span, hir::TyKind::Path(qpath))),
20712072
self.arena.alloc(hir::PathSegment::new(

compiler/rustc_ast_lowering/src/lib.rs

+43-8
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle, StashKey};
5555
use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
5656
use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
5757
use rustc_hir::{
58-
self as hir, ConstArg, GenericArg, HirId, ItemLocalMap, MissingLifetimeKind, ParamName,
59-
TraitCandidate,
58+
self as hir, ConstArg, GenericArg, HirId, ItemLocalMap, LangItem, MissingLifetimeKind,
59+
ParamName, TraitCandidate,
6060
};
6161
use rustc_index::{Idx, IndexSlice, IndexVec};
6262
use rustc_macros::extension;
@@ -765,8 +765,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
765765
res
766766
}
767767

768-
fn make_lang_item_qpath(&mut self, lang_item: hir::LangItem, span: Span) -> hir::QPath<'hir> {
769-
hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, None))
768+
fn make_lang_item_qpath(
769+
&mut self,
770+
lang_item: hir::LangItem,
771+
span: Span,
772+
args: Option<&'hir hir::GenericArgs<'hir>>,
773+
) -> hir::QPath<'hir> {
774+
hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
770775
}
771776

772777
fn make_lang_item_path(
@@ -1277,6 +1282,32 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
12771282
let lifetime = self.lower_lifetime(&region);
12781283
hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
12791284
}
1285+
TyKind::PinnedRef(region, mt) => {
1286+
let region = region.unwrap_or_else(|| {
1287+
let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1288+
self.resolver.get_lifetime_res(t.id)
1289+
{
1290+
debug_assert_eq!(start.plus(1), end);
1291+
start
1292+
} else {
1293+
self.next_node_id()
1294+
};
1295+
let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1296+
Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1297+
});
1298+
let lifetime = self.lower_lifetime(&region);
1299+
let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1300+
let span = self.lower_span(t.span);
1301+
let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1302+
let args = self.arena.alloc(hir::GenericArgs {
1303+
args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1304+
constraints: &[],
1305+
parenthesized: hir::GenericArgsParentheses::No,
1306+
span_ext: span,
1307+
});
1308+
let path = self.make_lang_item_qpath(LangItem::Pin, span, Some(args));
1309+
hir::TyKind::Path(path)
1310+
}
12801311
TyKind::BareFn(f) => {
12811312
let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
12821313
hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy {
@@ -1845,10 +1876,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
18451876
// Given we are only considering `ImplicitSelf` types, we needn't consider
18461877
// the case where we have a mutable pattern to a reference as that would
18471878
// no longer be an `ImplicitSelf`.
1848-
TyKind::Ref(_, mt) if mt.ty.kind.is_implicit_self() => match mt.mutbl {
1849-
hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1850-
hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1851-
},
1879+
TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
1880+
if mt.ty.kind.is_implicit_self() =>
1881+
{
1882+
match mt.mutbl {
1883+
hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1884+
hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1885+
}
1886+
}
18521887
_ => hir::ImplicitSelfKind::None,
18531888
}
18541889
}),

compiler/rustc_ast_lowering/src/lifetime_collector.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ impl<'ast> Visitor<'ast> for LifetimeCollectVisitor<'ast> {
9595
visit::walk_ty(self, t);
9696
self.current_binders.pop();
9797
}
98-
TyKind::Ref(None, _) => {
98+
TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
9999
self.record_elided_anchor(t.id, t.span);
100100
visit::walk_ty(self, t);
101101
}

compiler/rustc_ast_passes/src/feature_gate.rs

+1
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
546546
gate_all!(mut_ref, "mutable by-reference bindings are experimental");
547547
gate_all!(global_registration, "global registration is experimental");
548548
gate_all!(return_type_notation, "return type notation is experimental");
549+
gate_all!(pin_ergonomics, "pinned reference syntax is experimental");
549550

550551
if !visitor.features.never_patterns {
551552
if let Some(spans) = spans.get(&sym::never_patterns) {

compiler/rustc_ast_pretty/src/pprust/state.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,12 @@ impl<'a> State<'a> {
11631163
self.print_opt_lifetime(lifetime);
11641164
self.print_mt(mt, false);
11651165
}
1166+
ast::TyKind::PinnedRef(lifetime, mt) => {
1167+
self.word("&");
1168+
self.print_opt_lifetime(lifetime);
1169+
self.word("pin ");
1170+
self.print_mt(mt, true);
1171+
}
11661172
ast::TyKind::Never => {
11671173
self.word("!");
11681174
}

compiler/rustc_hir/src/hir.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
use std::fmt;
22

3-
use rustc_ast as ast;
43
use rustc_ast::util::parser::ExprPrecedence;
54
use rustc_ast::{
6-
Attribute, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitKind,
7-
TraitObjectSyntax, UintTy,
5+
self as ast, Attribute, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label,
6+
LitKind, TraitObjectSyntax, UintTy,
87
};
98
pub use rustc_ast::{
109
BinOp, BinOpKind, BindingMode, BorrowKind, ByRef, CaptureBy, ImplPolarity, IsAuto, Movability,

compiler/rustc_parse/src/parser/ty.rs

+35-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ use rustc_ast::util::case::Case;
44
use rustc_ast::{
55
self as ast, BareFnTy, BoundAsyncness, BoundConstness, BoundPolarity, DUMMY_NODE_ID, FnRetTy,
66
GenericBound, GenericBounds, GenericParam, Generics, Lifetime, MacCall, MutTy, Mutability,
7-
PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax, Ty, TyKind,
7+
Pinnedness, PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax, Ty,
8+
TyKind,
89
};
910
use rustc_errors::{Applicability, PResult};
1011
use rustc_span::symbol::{Ident, kw, sym};
@@ -487,7 +488,10 @@ impl<'a> Parser<'a> {
487488
fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
488489
let and_span = self.prev_token.span;
489490
let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime());
490-
let mut mutbl = self.parse_mutability();
491+
let (pinned, mut mutbl) = match self.parse_pin_and_mut() {
492+
Some(pin_mut) => pin_mut,
493+
None => (Pinnedness::Not, self.parse_mutability()),
494+
};
491495
if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() {
492496
// A lifetime is invalid here: it would be part of a bare trait bound, which requires
493497
// it to be followed by a plus, but we disallow plus in the pointee type.
@@ -523,7 +527,35 @@ impl<'a> Parser<'a> {
523527
self.bump_with((dyn_tok, dyn_tok_sp));
524528
}
525529
let ty = self.parse_ty_no_plus()?;
526-
Ok(TyKind::Ref(opt_lifetime, MutTy { ty, mutbl }))
530+
Ok(match pinned {
531+
Pinnedness::Not => TyKind::Ref(opt_lifetime, MutTy { ty, mutbl }),
532+
Pinnedness::Pinned => TyKind::PinnedRef(opt_lifetime, MutTy { ty, mutbl }),
533+
})
534+
}
535+
536+
/// Parses `pin` and `mut` annotations on references.
537+
///
538+
/// It must be either `pin const` or `pin mut`.
539+
pub(crate) fn parse_pin_and_mut(&mut self) -> Option<(Pinnedness, Mutability)> {
540+
if self.token.is_ident_named(sym::pin) {
541+
let result = self.look_ahead(1, |token| {
542+
if token.is_keyword(kw::Const) {
543+
Some((Pinnedness::Pinned, Mutability::Not))
544+
} else if token.is_keyword(kw::Mut) {
545+
Some((Pinnedness::Pinned, Mutability::Mut))
546+
} else {
547+
None
548+
}
549+
});
550+
if result.is_some() {
551+
self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
552+
self.bump();
553+
self.bump();
554+
}
555+
result
556+
} else {
557+
None
558+
}
527559
}
528560

529561
// Parses the `typeof(EXPR)`.

compiler/rustc_passes/src/hir_stats.rs

+1
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,7 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> {
579579
Array,
580580
Ptr,
581581
Ref,
582+
PinnedRef,
582583
BareFn,
583584
Never,
584585
Tup,

compiler/rustc_resolve/src/late.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -779,7 +779,7 @@ impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'r
779779
let prev = self.diag_metadata.current_trait_object;
780780
let prev_ty = self.diag_metadata.current_type_path;
781781
match &ty.kind {
782-
TyKind::Ref(None, _) => {
782+
TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
783783
// Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
784784
// NodeId `ty.id`.
785785
// This span will be used in case of elision failure.
@@ -2326,7 +2326,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
23262326
impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
23272327
fn visit_ty(&mut self, ty: &'ra Ty) {
23282328
trace!("FindReferenceVisitor considering ty={:?}", ty);
2329-
if let TyKind::Ref(lt, _) = ty.kind {
2329+
if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
23302330
// See if anything inside the &thing contains Self
23312331
let mut visitor =
23322332
SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };

compiler/rustc_resolve/src/late/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3482,7 +3482,7 @@ struct LifetimeFinder<'ast> {
34823482

34833483
impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
34843484
fn visit_ty(&mut self, t: &'ast Ty) {
3485-
if let TyKind::Ref(_, mut_ty) = &t.kind {
3485+
if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
34863486
self.seen.push(t);
34873487
if t.span.lo() == self.lifetime.lo() {
34883488
self.found = Some(&mut_ty.ty);

src/tools/clippy/clippy_utils/src/ast_utils.rs

+3
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,9 @@ pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
753753
(Ref(ll, l), Ref(rl, r)) => {
754754
both(ll.as_ref(), rl.as_ref(), |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty)
755755
},
756+
(PinnedRef(ll, l), PinnedRef(rl, r)) => {
757+
both(ll.as_ref(), rl.as_ref(), |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty)
758+
},
756759
(BareFn(l), BareFn(r)) => {
757760
l.safety == r.safety
758761
&& eq_ext(&l.ext, &r.ext)

src/tools/rustfmt/src/types.rs

+12-4
Original file line numberDiff line numberDiff line change
@@ -827,7 +827,8 @@ impl Rewrite for ast::Ty {
827827

828828
rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
829829
}
830-
ast::TyKind::Ref(ref lifetime, ref mt) => {
830+
ast::TyKind::Ref(ref lifetime, ref mt)
831+
| ast::TyKind::PinnedRef(ref lifetime, ref mt) => {
831832
let mut_str = format_mutability(mt.mutbl);
832833
let mut_len = mut_str.len();
833834
let mut result = String::with_capacity(128);
@@ -861,6 +862,13 @@ impl Rewrite for ast::Ty {
861862
cmnt_lo = lifetime.ident.span.hi();
862863
}
863864

865+
if let ast::TyKind::PinnedRef(..) = self.kind {
866+
result.push_str("pin ");
867+
if ast::Mutability::Not == mt.mutbl {
868+
result.push_str("const ");
869+
}
870+
}
871+
864872
if ast::Mutability::Mut == mt.mutbl {
865873
let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
866874
let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
@@ -1260,9 +1268,9 @@ pub(crate) fn can_be_overflowed_type(
12601268
) -> bool {
12611269
match ty.kind {
12621270
ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1263-
ast::TyKind::Ref(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
1264-
can_be_overflowed_type(context, &*mutty.ty, len)
1265-
}
1271+
ast::TyKind::Ref(_, ref mutty)
1272+
| ast::TyKind::PinnedRef(_, ref mutty)
1273+
| ast::TyKind::Ptr(ref mutty) => can_be_overflowed_type(context, &*mutty.ty, len),
12661274
_ => false,
12671275
}
12681276
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// See #130494
2+
3+
#![feature(pin_ergonomics)]
4+
#![allow(incomplete_features)]
5+
6+
fn f(x: &pin const i32) {}
7+
fn g<'a>(x: & 'a pin const i32) {}
8+
fn h<'a>(x: & 'a pin
9+
mut i32) {}
10+
fn i(x: &pin mut i32) {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// See #130494
2+
3+
#![feature(pin_ergonomics)]
4+
#![allow(incomplete_features)]
5+
6+
fn f(x: &pin const i32) {}
7+
fn g<'a>(x: &'a pin const i32) {}
8+
fn h<'a>(x: &'a pin mut i32) {}
9+
fn i(x: &pin mut i32) {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//@ check-pass
2+
#![feature(pin_ergonomics)]
3+
#![allow(dead_code, incomplete_features)]
4+
5+
// Handle the case where there's ambiguity between pin as a contextual keyword and pin as a path.
6+
7+
struct Foo;
8+
9+
mod pin {
10+
pub struct Foo;
11+
}
12+
13+
fn main() {
14+
let _x: &pin ::Foo = &pin::Foo;
15+
}

0 commit comments

Comments
 (0)