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
71 changes: 58 additions & 13 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2565,6 +2565,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 All @@ -2576,6 +2578,17 @@ impl TyKind {
matches!(self, TyKind::ImplicitSelf)
}

pub fn as_implicit_self_maybe_wrapped_in_view(&self) -> Option<ViewKind> {
Copy link
Copy Markdown
Contributor Author

@scrabsha scrabsha May 11, 2026

Choose a reason for hiding this comment

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

similarly, this method name is very very very meh

View changes since the review

match self {
TyKind::ImplicitSelf => Some(ViewKind::Full),
TyKind::View(ty, fields) if ty.kind.is_implicit_self() => {
let fields = fields.clone();
Some(ViewKind::Partial { fields })
}
_ => None,
}
}

pub fn is_unit(&self) -> bool {
matches!(self, TyKind::Tup(tys) if tys.is_empty())
}
Expand Down Expand Up @@ -2929,6 +2942,12 @@ 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`
Expand All @@ -2955,28 +2974,46 @@ impl SelfKind {
}
}

pub type ExplicitSelf = Spanned<SelfKind>;
/// Represents how a type is viewed.
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum ViewKind {
/// `T`. All the fields can be observed.
Full,
/// `T.{ foo, bar }`. Only `foo` and `bar` can be observed.
// FIXME(scrabsha): in the future, we may want to express more complex situations, such as
// mutably observing some fields while immutably observing others. Something like
// `T.{ foo, mut bar }`.
Partial {
#[visitable(ignore)]
fields: ThinVec<Ident>,
},
}

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))),
TyKind::Ref(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
let (kind, view, span) = match self.ty.kind {
ref kind if let Some(view) = kind.as_implicit_self_maybe_wrapped_in_view() => {
(SelfKind::Value(mutbl), view, self.pat.span)
}
TyKind::Ref(lt, MutTy { ref ty, mutbl })
if let Some(view) = ty.kind.as_implicit_self_maybe_wrapped_in_view() =>
{
(SelfKind::Region(lt, mutbl), view, self.pat.span)
}
TyKind::PinnedRef(lt, MutTy { ref ty, mutbl })
if ty.kind.is_implicit_self() =>
if let Some(view) = ty.kind.as_implicit_self_maybe_wrapped_in_view() =>
{
Some(respan(self.pat.span, SelfKind::Pinned(lt, mutbl)))
(SelfKind::Pinned(lt, mutbl), view, self.pat.span)
}
_ => Some(respan(
self.pat.span.to(self.ty.span),
SelfKind::Explicit(self.ty.clone(), mutbl),
)),
_ => (SelfKind::Explicit(self.ty.clone(), mutbl), ViewKind::Full, self.ty.span),
};
let param = respan(span, SelfParam { view, kind });
return Some(param);
Comment on lines +2999 to +3016
Copy link
Copy Markdown
Contributor Author

@scrabsha scrabsha May 11, 2026

Choose a reason for hiding this comment

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

i am not happy at all with this code, but i cannot think of a better way to express things. opinions are welcome.

View changes since the review

}
}
None
Expand All @@ -2994,13 +3031,21 @@ impl Param {
/// Builds a `Param` object from `ExplicitSelf`.
pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
let span = eself.span.to(eself_ident.span);
let infer_ty = Box::new(Ty {
let mut infer_ty = Box::new(Ty {
id: DUMMY_NODE_ID,
kind: TyKind::ImplicitSelf,
span: eself_ident.span,
tokens: None,
});
let (mutbl, ty) = match eself.node {
if let ViewKind::Partial { fields } = eself.node.view {
infer_ty = Box::new(Ty {
id: DUMMY_NODE_ID,
kind: TyKind::View(infer_ty, fields),
span: eself_ident.span,
tokens: None,
});
}
let (mutbl, ty) = match eself.node.kind {
SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
SelfKind::Value(mutbl) => (mutbl, infer_ty),
SelfKind::Region(lt, mutbl) => (
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
26 changes: 24 additions & 2 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,20 @@ impl<'a> State<'a> {
}
}

fn print_view(&mut self, fields: &[Ident]) {
self.word(".{");

if !fields.is_empty() {
self.space();
self.commasep(Consistent, fields, |s, field| {
s.print_ident(*field);
});
self.space();
}

self.word("}");
}
Comment thread
scrabsha marked this conversation as resolved.

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 +1451,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,7 +2071,7 @@ 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")
Expand All @@ -2078,6 +2096,10 @@ impl<'a> State<'a> {
self.print_type(typ)
}
}

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
3 changes: 2 additions & 1 deletion compiler/rustc_parse/src/parser/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1900,7 +1900,8 @@ impl<'a> Parser<'a> {
let lexpr = self.parse_expr_labeled(label, true)?;
self.dcx().emit_err(errors::LabeledLoopInBreak {
span: lexpr.span,
sub: errors::WrapInParentheses::Expression {
sub: errors::WrapInParentheses::NonMacro {
kind: errors::WrapInParenthesesNodeKind::Expression,
left: lexpr.span.shrink_to_lo(),
right: lexpr.span.shrink_to_hi(),
},
Expand Down
Loading
Loading