Skip to content
Open
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
78 changes: 66 additions & 12 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2480,6 +2480,23 @@ impl Ty {
final_ty
}

pub fn extract_view(&self) -> Option<(Self, &[Ident])> {
match &self.kind {
TyKind::View(inner, fields) => Some((*inner.clone(), fields)),

TyKind::Ref(lifetime, MutTy { ty, mutbl }) => {
let (inner, fields) = ty.extract_view()?;
let kind =
TyKind::Ref(*lifetime, MutTy { ty: Box::new(inner.clone()), mutbl: *mutbl });
let ty = Ty { id: self.id, kind, span: self.span, tokens: self.tokens.clone() };

Some((ty, fields))
}

_ => None,
}
}

pub fn is_maybe_parenthesised_infer(&self) -> bool {
match &self.kind {
TyKind::Infer => true,
Expand Down Expand Up @@ -2565,6 +2582,8 @@ pub enum TyKind {
/// Usually not written directly in user code but indirectly via the macro
/// `core::field::field_of!(...)`.
FieldOf(Box<Ty>, Option<Ident>, Ident),
/// A view of a type. `T.{ field_1, field_2 }`.
View(Box<Ty>, #[visitable(ignore)] ThinVec<Ident>),
/// Sometimes we need a dummy value when no error has occurred.
Dummy,
/// Placeholder for a kind that has failed to be defined.
Expand Down Expand Up @@ -2660,6 +2679,20 @@ pub enum TraitObjectSyntax {
None = 1,
}

/// Represents how a reference is viewed.
// FIXME(scrabsha): move this to a new variant of `Mutability` when viewing of non-reference types
// is implemented.
Comment on lines +2682 to +2684
Copy link
Copy Markdown
Contributor Author

@scrabsha scrabsha May 7, 2026

Choose a reason for hiding this comment

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

is this still relevant?

View changes since the review

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum ViewKind {
/// `&mut T`. All the fields can be observed.
Full,
/// `&mut T.{ foo, bar }`. Only `foo` and `bar` can be observed.
Comment on lines +2687 to +2689
Copy link
Copy Markdown
Contributor Author

@scrabsha scrabsha May 8, 2026

Choose a reason for hiding this comment

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

the &s are not relevant anymore

View changes since the review

Partial {
#[visitable(ignore)]
fields: ThinVec<Ident>,
},
}

/// SAFETY: `TraitObjectSyntax` only has 3 data-less variants which means
/// it can be represented with a `u2`. We use `repr(u8)` to guarantee the
/// discriminants of the variants are no greater than `3`.
Expand Down Expand Up @@ -2929,13 +2962,19 @@ pub struct Param {
/// Alternative representation for `Arg`s describing `self` parameter of methods.
///
/// E.g., `&mut self` as in `fn foo(&mut self)`.
#[derive(Clone, Encodable, Decodable, Debug)]
pub struct SelfParam {
pub kind: SelfKind,
pub view: ViewKind,
}

#[derive(Clone, Encodable, Decodable, Debug)]
pub enum SelfKind {
/// `self`, `mut self`
Value(Mutability),
/// `&'lt self`, `&'lt mut self`
/// `&'lt self`, `&'lt mut self`, `&'lt mut self.{ a, b }`
Region(Option<Lifetime>, Mutability),
/// `&'lt pin const self`, `&'lt pin mut self`
/// `&'lt pin const self`, `&'lt pin mut self`, `&'lt pin mut self.{ a, b }`.
Comment on lines +2975 to +2977
Copy link
Copy Markdown
Contributor Author

@scrabsha scrabsha May 7, 2026

Choose a reason for hiding this comment

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

the comments can be reverted, the view is not stored here anymore

View changes since the review

Pinned(Option<Lifetime>, Mutability),
/// `self: TYPE`, `mut self: TYPE`
Explicit(Box<Ty>, Mutability),
Expand All @@ -2955,28 +2994,35 @@ impl SelfKind {
}
}

pub type ExplicitSelf = Spanned<SelfKind>;
pub type ExplicitSelf = Spanned<SelfParam>;

impl Param {
/// Attempts to cast parameter to `ExplicitSelf`.
pub fn to_self(&self) -> Option<ExplicitSelf> {
if let PatKind::Ident(BindingMode(ByRef::No, mutbl), ident, _) = self.pat.kind {
if ident.name == kw::SelfLower {
return match self.ty.kind {
TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
let (ty, view) = match self.ty.extract_view() {
Some((this, fields)) => {
(this, ViewKind::Partial { fields: ThinVec::from(fields) })
}
None => (*self.ty.clone(), ViewKind::Full),
};

let (kind, span) = match ty.kind {
TyKind::ImplicitSelf => (SelfKind::Value(mutbl), self.pat.span),
TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
(SelfKind::Region(lt, mutbl), self.pat.span)
}
TyKind::PinnedRef(lt, MutTy { ref ty, mutbl })
if ty.kind.is_implicit_self() =>
{
Some(respan(self.pat.span, SelfKind::Pinned(lt, mutbl)))
(SelfKind::Pinned(lt, mutbl), self.pat.span)
}
_ => Some(respan(
self.pat.span.to(self.ty.span),
SelfKind::Explicit(self.ty.clone(), mutbl),
)),
_ => (SelfKind::Explicit(Box::new(ty), mutbl), self.ty.span),
};

let param = respan(span, SelfParam { view, kind });
return Some(param);
}
}
None
Expand All @@ -3000,7 +3046,7 @@ impl Param {
span: eself_ident.span,
tokens: None,
});
let (mutbl, ty) = match eself.node {
let (mutbl, mut ty) = match eself.node.kind {
SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
SelfKind::Value(mutbl) => (mutbl, infer_ty),
SelfKind::Region(lt, mutbl) => (
Expand All @@ -3022,6 +3068,14 @@ impl Param {
}),
),
};
if let ViewKind::Partial { fields } = eself.node.view {
ty = Box::new(Ty {
id: DUMMY_NODE_ID,
kind: TyKind::View(ty, fields),
span,
tokens: None,
});
}
Param {
attrs,
pat: Box::new(Pat {
Expand Down
18 changes: 13 additions & 5 deletions compiler/rustc_ast/src/util/classify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ pub enum TrailingBrace<'a> {
/// Trailing brace in any other expression, such as `a + B {}`. We will
/// suggest wrapping the innermost expression in parentheses: `a + (B {})`.
Expr(&'a ast::Expr),
/// Trailing brace in a type, like the one in `&Foo.{ bar }`
Type(&'a ast::Ty),
}

/// If an expression ends with `}`, returns the innermost expression ending in the `}`
Expand Down Expand Up @@ -205,7 +207,7 @@ pub fn expr_trailing_brace(mut expr: &ast::Expr) -> Option<TrailingBrace<'_>> {
| ConstBlock(_) => break Some(TrailingBrace::Expr(expr)),

Cast(_, ty) => {
break type_trailing_braced_mac_call(ty).map(TrailingBrace::MacCall);
break type_trailing_brace(ty);
}

MacCall(mac) => {
Expand Down Expand Up @@ -246,13 +248,17 @@ pub fn expr_trailing_brace(mut expr: &ast::Expr) -> Option<TrailingBrace<'_>> {
}
}

/// If the type's last token is `}`, it must be due to a braced macro call, such
/// as in `*const brace! { ... }`. Returns that trailing macro call.
fn type_trailing_braced_mac_call(mut ty: &ast::Ty) -> Option<&ast::MacCall> {
/// If a type ends with `}`, return the innermost node ending with the `}`.
///
/// This may be caused by a macro call (`*const brace! { ... }`) or a view type
/// (`&Foo.{ bar }`).
fn type_trailing_brace(mut ty: &ast::Ty) -> Option<TrailingBrace<'_>> {
loop {
match &ty.kind {
ast::TyKind::MacCall(mac) => {
break (mac.args.delim == Delimiter::Brace).then_some(mac);
break (mac.args.delim == Delimiter::Brace)
.then_some(mac.as_ref())
.map(TrailingBrace::MacCall);
}

ast::TyKind::Ptr(mut_ty)
Expand All @@ -261,6 +267,8 @@ fn type_trailing_braced_mac_call(mut ty: &ast::Ty) -> Option<&ast::MacCall> {
ty = &mut_ty.ty;
}

ast::TyKind::View(..) => break Some(TrailingBrace::Type(ty)),

ast::TyKind::UnsafeBinder(binder) => {
ty = &binder.inner_ty;
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_ast/src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,7 @@ macro_rules! common_visitor_and_walkers {
UnsafeBinderTy,
UnsafeSource,
UseTreeKind,
ViewKind,
VisibilityKind,
WhereBoundPredicate,
WhereClause,
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1594,6 +1594,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
);
hir::TyKind::Err(guar)
}
TyKind::View(ty, _) => {
// FIXME(scrabsha): lower view types to HIR.
return self.lower_ty(ty, itctx);
}
TyKind::Dummy => panic!("`TyKind::Dummy` should never be lowered"),
};

Expand Down
28 changes: 22 additions & 6 deletions compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use rustc_ast::util::comments::{Comment, CommentStyle};
use rustc_ast::{
self as ast, AttrArgs, BindingMode, BlockCheckMode, ByRef, DelimArgs, GenericArg, GenericBound,
InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass, InlineAsmTemplatePiece, PatKind,
RangeEnd, RangeSyntax, Safety, SelfKind, Term, attr,
RangeEnd, RangeSyntax, Safety, SelfKind, Term, ViewKind, attr,
};
use rustc_span::edition::Edition;
use rustc_span::source_map::SourceMap;
Expand Down Expand Up @@ -1255,6 +1255,14 @@ impl<'a> State<'a> {
}
}

fn print_view(&mut self, fields: &[Ident]) {
self.word_space(".{");
self.commasep(Breaks::Inconsistent, fields, |s, field| {
s.print_ident(*field);
});
self.word_space(" }");
}
Comment on lines +1258 to +1264
Copy link
Copy Markdown
Contributor Author

@scrabsha scrabsha May 7, 2026

Choose a reason for hiding this comment

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

i'm 99% sure this is wrong somehow

as far as i know, there is no other node in the rust grammar that is only a list of identifiers separated by commas, so i don't have anything to draw inspiration from :/

i'll try to skim over the pprust module tomorrow to find a better way to do this.

View changes since the review


pub fn print_assoc_item_constraint(&mut self, constraint: &ast::AssocItemConstraint) {
self.print_ident(constraint.ident);
if let Some(args) = constraint.gen_args.as_ref() {
Expand Down Expand Up @@ -1437,6 +1445,10 @@ impl<'a> State<'a> {
self.end(ib);
self.pclose();
}
ast::TyKind::View(ty, fields) => {
self.print_type(ty);
self.print_view(fields);
}
}
self.end(ib);
}
Expand Down Expand Up @@ -2053,31 +2065,35 @@ impl<'a> State<'a> {
}

fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
match &explicit_self.node {
match &explicit_self.node.kind {
SelfKind::Value(m) => {
self.print_mutability(*m, false);
self.word("self")
self.word("self");
}
SelfKind::Region(lt, m) => {
self.word("&");
self.print_opt_lifetime(lt);
self.print_mutability(*m, false);
self.word("self")
self.word("self");
}
SelfKind::Pinned(lt, m) => {
self.word("&");
self.print_opt_lifetime(lt);
self.word("pin ");
self.print_mutability(*m, true);
self.word("self")
self.word("self");
}
SelfKind::Explicit(typ, m) => {
self.print_mutability(*m, false);
self.word("self");
self.word_space(":");
self.print_type(typ)
self.print_type(typ);
Comment on lines +2068 to +2090
Copy link
Copy Markdown
Contributor Author

@scrabsha scrabsha May 7, 2026

Choose a reason for hiding this comment

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

these edits come from an earlier version of this change, let's revert them

View changes since the review

}
}

if let ViewKind::Partial { fields } = &explicit_self.node.view {
self.print_view(fields);
}
}

fn print_coroutine_kind(&mut self, coroutine_kind: ast::CoroutineKind) {
Expand Down
31 changes: 30 additions & 1 deletion compiler/rustc_ast_pretty/src/pprust/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use rustc_ast as ast;
use rustc_span::{DUMMY_SP, Ident, create_default_session_globals_then};
use thin_vec::ThinVec;
use thin_vec::{ThinVec, thin_vec};

use super::*;

Expand All @@ -22,6 +22,12 @@ fn variant_to_string(var: &ast::Variant) -> String {
to_string(|s| s.print_variant(var))
}

fn ty_to_string(ty: &ast::Ty) -> String {
to_string(|s| {
s.print_type(ty);
})
}

#[test]
fn test_fun_to_string() {
create_default_session_globals_then(|| {
Expand Down Expand Up @@ -60,3 +66,26 @@ fn test_variant_to_string() {
assert_eq!(varstr, "principal_skinner");
})
}

#[test]
fn test_field_view() {
create_default_session_globals_then(|| {
let ty = ast::Ty {
id: ast::DUMMY_NODE_ID,
kind: ast::TyKind::View(
Box::new(ast::Ty {
id: ast::DUMMY_NODE_ID,
kind: ast::TyKind::Dummy,
span: DUMMY_SP,
tokens: None,
}),
thin_vec![Ident::from_str("milhouse"), Ident::from_str("apu")],
),
span: DUMMY_SP,
tokens: None,
};

let ty_str = ty_to_string(&ty);
assert_eq!(ty_str, "(/*DUMMY*/).{ milhouse, apu }");
});
}
8 changes: 6 additions & 2 deletions compiler/rustc_builtin_macros/src/deriving/generic/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
//! when specifying impls to be derived.

pub(crate) use Ty::*;
use rustc_ast::{self as ast, Expr, GenericArg, GenericParamKind, Generics, SelfKind, TyKind};
use rustc_ast::{
self as ast, Expr, GenericArg, GenericParamKind, Generics, SelfKind, TyKind, ViewKind,
};
use rustc_expand::base::ExtCtxt;
use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, respan};
use thin_vec::ThinVec;
Expand Down Expand Up @@ -200,6 +202,8 @@ impl Bounds {
pub(crate) fn get_explicit_self(cx: &ExtCtxt<'_>, span: Span) -> (Box<Expr>, ast::ExplicitSelf) {
// This constructs a fresh `self` path.
let self_path = cx.expr_self(span);
let self_ty = respan(span, SelfKind::Region(None, ast::Mutability::Not));
let kind = SelfKind::Region(None, ast::Mutability::Not);
let view = ViewKind::Full;
let self_ty = respan(span, ast::SelfParam { kind, view });
(self_path, self_ty)
}
24 changes: 19 additions & 5 deletions compiler/rustc_parse/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,11 +1058,9 @@ pub(crate) struct LabeledLoopInBreak {

#[derive(Subdiagnostic)]
pub(crate) enum WrapInParentheses {
#[multipart_suggestion(
"wrap the expression in parentheses",
applicability = "machine-applicable"
)]
Expression {
#[multipart_suggestion("wrap the {$kind} in parentheses", applicability = "machine-applicable")]
NonMacro {
kind: WrapInParenthesesNodeKind,
#[suggestion_part(code = "(")]
left: Span,
#[suggestion_part(code = ")")]
Expand All @@ -1080,6 +1078,22 @@ pub(crate) enum WrapInParentheses {
},
}

pub(crate) enum WrapInParenthesesNodeKind {
Expression,
Type,
}

impl IntoDiagArg for WrapInParenthesesNodeKind {
fn into_diag_arg(self, _path: &mut Option<PathBuf>) -> DiagArgValue {
let str = match self {
WrapInParenthesesNodeKind::Expression => "expression",
WrapInParenthesesNodeKind::Type => "type",
};

DiagArgValue::Str(Cow::Borrowed(str))
}
}

#[derive(Diagnostic)]
#[diag("this is a block expression, not an array")]
pub(crate) struct ArrayBracketsInsteadOfBraces {
Expand Down
Loading
Loading