rust-lang/rust · #165764
view-types: handle field accesses
compiler/rustc_hir_typeck/src/diagnostics.rs12 + / 0 −
@@ -1402,3 +1402,15 @@ pub(crate) struct DelegationInvalidAdtForReturnWrapping { pub span: Span, pub adt_name: String, }++#[derive(Diagnostic)]+#[diag("field `{$field}` cannot be accessed")]+pub(crate) struct FieldNotPartOfView<'tcx> {+ pub(crate) field: Symbol,+ #[primary_span]+ pub(crate) span: Span,+ #[note("this expression has type {$ty}, of which only {$fields} can be accessed")]+ pub(crate) note: Span,+ pub(crate) ty: Ty<'tcx>,+ pub(crate) fields: DiagSymbolList,+}compiler/rustc_hir_typeck/src/expr.rs120 + / 44 −
@@ -6,6 +6,7 @@ //! See [`rustc_hir_analysis::check`] for more context on type checking in general. use std::borrow::Cow;+use std::ops::ControlFlow; use rustc_abi::{FIRST_VARIANT, FieldIdx}; use rustc_ast as ast;@@ -20,15 +21,19 @@ use rustc_errors::{ }; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res};+use rustc_hir::def_id::DefId; use rustc_hir::{ExprKind, HirId, QPath, is_range_literal};+use rustc_hir_analysis::autoderef::Autoderef; use rustc_hir_analysis::diagnostics::NoVariantNamed; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; use rustc_infer::infer::{self, RegionVariableOrigin}; use rustc_infer::traits::WellFormedLoc; use rustc_infer::traits::query::NoSolution; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError};-use rustc_middle::ty::{self, AdtKind, ConstKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized};+use rustc_middle::ty::{+ self, AdtKind, ConstKind, FieldInfo, GenericArgs, Ty, TypeVisitableExt, Unnormalized,+}; use rustc_session::diagnostics::feature_err; use rustc_span::hygiene::DesugaringKind; use rustc_span::{Ident, Span, Spanned, Symbol, bug, kw, span_bug, sym};@@ -42,9 +47,9 @@ use crate::coercion::CoerceMany; use crate::diagnostics::{ AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr, BaseExpressionDoubleDotRemove, CantDereference, DelegationInvalidAdtForReturnWrapping,- ExprParenthesesNeeded, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,- NakedAsmOutsideNakedFn, NoFieldOnVariant, ReturnLikeStatementKind, StructExprNonExhaustive,- YieldExprOutsideOfCoroutine,+ ExprParenthesesNeeded, FieldMultiplySpecifiedInInitializer, FieldNotPartOfView,+ FunctionalRecordUpdateOnNonStruct, NakedAsmOutsideNakedFn, NoFieldOnVariant,+ ReturnLikeStatementKind, StructExprNonExhaustive, YieldExprOutsideOfCoroutine, }; use crate::op::contains_let_in_chain; use crate::{@@ -2326,48 +2331,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut autoderef = self.autoderef(expr.span, base_ty); while let Some((deref_base_ty, _)) = autoderef.next() { debug!("deref_base_ty: {:?}", deref_base_ty);- match deref_base_ty.kind() {- ty::Adt(base_def, args) if !base_def.is_enum() => {- debug!("struct named {:?}", deref_base_ty);- // we don't care to report errors for a struct if the struct itself is tainted- if let Err(guar) = base_def.non_enum_variant().has_errors() {- return Ty::new_error(self.tcx(), guar);- }-- let (ident, def_scope) =- self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.mod_id);-- if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {- self.write_field_index(expr.hir_id, idx);-- let adjustments = self.adjust_steps(&autoderef);- if field.vis.is_accessible_from(def_scope, self.tcx) {- self.apply_adjustments(base, adjustments);- self.register_predicates(autoderef.into_obligations());-- self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);- return self.field_ty(expr.span, field, *args);- }-- // The field is not accessible, fall through to error reporting.- private_candidate = Some((adjustments, base_def.did()));- }+ match self.check_field_access_for_deref_step(+ expr,+ base,+ field,+ &autoderef,+ deref_base_ty,+ base_ty,+ ) {+ ControlFlow::Continue(private_candidate_) => {+ private_candidate = private_candidate.xor(private_candidate_); }- ty::Tuple(tys) => {- if let Ok(index) = field.as_str().parse::<usize>() {- if field.name == sym::integer(index) {- if let Some(&field_ty) = tys.get(index) {- let adjustments = self.adjust_steps(&autoderef);- self.apply_adjustments(base, adjustments);- self.register_predicates(autoderef.into_obligations());-- self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));- return field_ty;- }- }- }+ ControlFlow::Break(ty) => {+ self.register_predicates(autoderef.into_obligations());+ return ty; }- _ => {} } } // We failed to check the expression, report an error.@@ -2480,6 +2458,104 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ty::new_error(self.tcx(), guar) } + fn check_field_access_for_deref_step(+ &self,+ expr: &'tcx rustc_hir::Expr<'tcx>,+ base: &'tcx rustc_hir::Expr<'tcx>,+ field: Ident,+ autoderef: &Autoderef<'_, 'tcx>,+ deref_base_ty: Ty<'tcx>,+ base_ty: Ty<'tcx>,+ ) -> ControlFlow<Ty<'tcx>, Option<(Vec<Adjustment<'tcx>>, DefId)>> {+ let (field_ty, field_idx) = match deref_base_ty.kind() {+ ty::Adt(base_def, args) | ty::View(base_def, args, _) if !base_def.is_enum() => {+ debug!("struct named {:?}", deref_base_ty);+ // we don't care to report errors for a struct if the struct itself is tainted+ if let Err(guar) = base_def.non_enum_variant().has_errors() {+ return ControlFlow::Break(Ty::new_error(self.tcx(), guar));+ }++ let (ident, def_scope) =+ self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.mod_id);++ let Some((idx, field)) = self.find_adt_field(*base_def, ident) else {+ return ControlFlow::Continue(None);+ };++ if !field.vis.is_accessible_from(def_scope, self.tcx) {+ // The field is not accessible, fall through to error reporting.+ let adjustments = self.adjust_steps(autoderef);+ return ControlFlow::Continue(Some((adjustments, base_def.did())));+ }++ self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);++ (self.field_ty(expr.span, field, *args), idx)+ }++ ty::Tuple(tys) => {+ let Ok(index) = field.as_str().parse::<usize>() else {+ return ControlFlow::Continue(None);+ };++ if field.name != sym::integer(index) {+ return ControlFlow::Continue(None);+ }++ let Some(&field_ty) = tys.get(index) else {+ return ControlFlow::Continue(None);+ };++ (field_ty, FieldIdx::from_usize(index))+ }++ _ => return ControlFlow::Continue(None),+ };++ if let ty::View(_, _, fields) = deref_base_ty.kind() {+ // check that the field we are accessing is part of the view+ let tuple_elems = match fields.kind() {+ ty::Tuple(fields) => fields,+ // FIXME(scrabsha): can we still have inferred views?+ _ => bug!("malformed view type viewed field set"),+ };+ let extract_frt = |ty: Ty<'tcx>| -> FieldInfo<_> {+ match ty.kind() {+ ty::Adt(base_def_, args_)+ if let Some(frt) =+ base_def_.field_representing_type_info(self.tcx(), *args_) =>+ {+ // sanity check: view types on enums are not a thing.+ debug_assert!(frt.variant.is_none());+ frt+ }++ _ => bug!("malformed view type viewed field set"),+ }+ };++ let mut field_idxs = tuple_elems.iter().map(extract_frt).map(|field| field.field_idx);+ if field_idxs.all(|viewed_idx| viewed_idx != field_idx) {+ let fields = tuple_elems.iter().map(extract_frt).map(|frt| frt.name).collect();+ let guar = self.tcx.dcx().emit_err(FieldNotPartOfView {+ field: field.name,+ span: field.span,+ fields,+ note: base.span,+ ty: base_ty,+ });+ return ControlFlow::Break(Ty::new_error(self.tcx, guar));+ }+ }++ let adjustments = self.adjust_steps(autoderef);+ self.apply_adjustments(base, adjustments);++ self.write_field_index(expr.hir_id, field_idx);++ ControlFlow::Break(field_ty)+ }+ fn check_expr_index( &self, base: &'tcx hir::Expr<'tcx>,compiler/rustc_middle/src/mir/statement.rs1 + / 1 −
@@ -144,7 +144,7 @@ impl<'tcx> PlaceTy<'tcx> { } } else { match self_ty.kind() {- ty::Adt(adt_def, args) if !adt_def.is_enum() => {+ ty::Adt(adt_def, args) | ty::View(adt_def, args, _) if !adt_def.is_enum() => { adt_def.non_enum_variant().fields[f].ty(tcx, *args) } ty::Closure(_, args) => Unnormalized::dummy(compiler/rustc_middle/src/ty/context.rs35 + / 0 −
@@ -2598,6 +2598,41 @@ impl<'tcx> TyCtxt<'tcx> { } } + /// with `cfg(debug_assertions)`, assert that the encoded representation of viewed fields is+ /// valid for a given ADT, and ICEs if not.+ pub fn debug_assert_encoded_viewed_fields_compatible(+ self,+ base_def: AdtDef<'tcx>,+ base_args: ty::GenericArgs<'tcx>,+ fields: Ty<'tcx>,+ ) {+ if cfg!(debug_assertions) {+ let base_ty = Ty::new_adt(self, base_def, base_args);++ let ty::Tuple(fields) = fields.kind() else {+ bug!("incompatible encoded viewed fields type: {fields:?}");+ };++ for field in *fields {+ let frt_args = match field.kind() {+ ty::Adt(def, args)+ if def.flags().contains(ty::AdtFlags::IS_FIELD_REPRESENTING_TYPE) =>+ {+ args+ }+ _ => bug!("malformed encoded viewed field type: {field:?}"),+ };++ let referred_ty = frt_args[0].as_type().expect("first FRT arg is type");++ assert_eq!(+ referred_ty, base_ty,+ "viewed field ({referred_ty:?}) does not refer to the base type ({base_ty:?})"+ );+ }+ }+ }+ fn emit_bug_args_compatible( self, def_id: DefId,compiler/rustc_middle/src/ty/sty.rs22 + / 3 −
@@ -835,16 +835,26 @@ impl<'tcx> Ty<'tcx> { args: GenericArgs<'tcx>, fields: &[FieldIdx], ) -> Ty<'tcx> {- tcx.debug_assert_args_compatible(def.did(), args);- tcx.debug_assert_adt_def_kind_compatible(def);- let base = Ty::new_adt(tcx, def, args); let fields = fields .iter() .map(|field| Ty::new_field_representing_type(tcx, base, FIRST_VARIANT, *field)); let fields = Ty::new_tup_from_iter(tcx, fields); + Ty::new_encoded_view(tcx, def, args, fields)+ }++ fn new_encoded_view(+ tcx: TyCtxt<'tcx>,+ def: AdtDef<'tcx>,+ args: GenericArgs<'tcx>,+ fields: Ty<'tcx>,+ ) -> Ty<'tcx> {+ tcx.debug_assert_args_compatible(def.did(), args);+ tcx.debug_assert_adt_def_kind_compatible(def);+ tcx.debug_assert_encoded_viewed_fields_compatible(def, args, fields);+ tcx.interners.intern_view(def, args, fields) } @@ -974,6 +984,15 @@ impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> { Ty::new_adt(interner, adt_def, args) } + fn new_view(+ interner: TyCtxt<'tcx>,+ adt_def: ty::AdtDef<'tcx>,+ args: ty::GenericArgs<'tcx>,+ fields: Ty<'tcx>,+ ) -> Self {+ Ty::new_encoded_view(interner, adt_def, args, fields)+ }+ fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self { Ty::new_foreign(interner, def_id) }compiler/rustc_passes/src/dead.rs1 + / 1 −
@@ -285,7 +285,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) { match self.typeck_results().expr_ty_adjusted(lhs).kind() {- ty::Adt(def, _) => {+ ty::Adt(def, _) | ty::View(def, _, _) => { let index = self.typeck_results().field_index(hir_id); self.insert_def_id(def.non_enum_variant().fields[index].did); }compiler/rustc_type_ir/src/inherent.rs2 + / 0 −
@@ -87,6 +87,8 @@ pub trait Ty<I: Interner<Ty = Self>>: fn new_adt(interner: I, adt_def: I::AdtDef, args: I::GenericArgs) -> Self; + fn new_view(interner: I, adt_def: I::AdtDef, args: I::GenericArgs, fields: I::Ty) -> Self;+ fn new_foreign(interner: I, def_id: I::ForeignId) -> Self; fn new_dynamic(interner: I, preds: I::BoundExistentialPredicates, region: Region<I>) -> Self;compiler/rustc_type_ir/src/relate.rs10 + / 0 −
@@ -392,6 +392,16 @@ pub fn structurally_relate_tys<I: Interner, R: TypeRelation<I>>( } } + (ty::View(a_def, a_args, a_fields), ty::View(b_def, b_args, b_fields))+ if a_def == b_def =>+ {+ let fields = relation.tys(a_fields, b_fields)?;++ relation.relate_ty_args(a, b, a_def.def_id().into(), a_args, b_args, |args| {+ Ty::new_view(cx, a_def, args, fields)+ })+ }+ (ty::Foreign(a_id), ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(cx, a_id)), (ty::Dynamic(a_obj, a_region), ty::Dynamic(b_obj, b_region)) => Ok(Ty::new_dynamic(compiler/rustc_type_ir/src/ty_kind.rs28 + / 18 −
@@ -468,21 +468,7 @@ impl<I: Interner> fmt::Debug for TyKind<I> { Int(i) => write!(f, "{i:?}"), Uint(u) => write!(f, "{u:?}"), Float(float) => write!(f, "{float:?}"),- Adt(d, s) => {- write!(f, "{d:?}")?;- let mut s = s.iter();- let first = s.next();- match first {- Some(first) => write!(f, "<{:?}", first)?,- None => return Ok(()),- };-- for arg in s {- write!(f, ", {:?}", arg)?;- }-- write!(f, ">")- }+ Adt(d, s) => debug_adt::<I>(f, d, s), Foreign(d) => f.debug_tuple("Foreign").field(d).finish(), Str => write!(f, "str"), Array(t, c) => write!(f, "[{t:?}; {c:?}]"),@@ -516,19 +502,43 @@ impl<I: Interner> fmt::Debug for TyKind<I> { } write!(f, ")") }+ ty::View(d, s, fields) => {+ write!(+ f,+ "view_type!({}.{{ {fields:?} }})",+ fmt::from_fn(|f| debug_adt::<I>(f, d, s))+ )+ } Alias(is_rigid, a) => f.debug_tuple("Alias").field(&is_rigid).field(&a).finish(), Param(p) => write!(f, "{p:?}"), Bound(d, b) => crate::debug_bound_var(f, *d, b), Placeholder(p) => write!(f, "{p:?}"), Infer(t) => write!(f, "{:?}", t), TyKind::Error(_) => write!(f, "{{type error}}"),-- // FIXME(scrabsha)- ty::View(..) => unimplemented!(), } } } +fn debug_adt<I: Interner>(+ f: &mut fmt::Formatter<'_>,+ d: &<I as Interner>::AdtDef,+ s: &<I as Interner>::GenericArgs,+) -> Result<(), fmt::Error> {+ write!(f, "{d:?}")?;+ let mut s = s.iter();+ let first = s.next();+ match first {+ Some(first) => write!(f, "<{:?}", first)?,+ None => return Ok(()),+ };++ for arg in s {+ write!(f, ", {:?}", arg)?;+ }++ write!(f, ">")+}+ impl<I: Interner> AliasTy<I> { pub fn new_from_args(interner: I, kind: AliasTyKind<I>, args: I::GenericArgs) -> AliasTy<I> { if cfg!(debug_assertions) {tests/ui/view-types/field-access.illegal.stderradded62 + / 0 −
@@ -0,0 +1,62 @@+error: field `b` cannot be accessed+ --> $DIR/field-access.rs:36:17+ |+LL | let _ = foo.b;+ | ^+ |+note: this expression has type &view_type!(Foo.{ a }), of which only `a` can be accessed+ --> $DIR/field-access.rs:36:13+ |+LL | let _ = foo.b;+ | ^^^++error: field `1` cannot be accessed+ --> $DIR/field-access.rs:43:18+ |+LL | let _ = &bar.1;+ | ^+ |+note: this expression has type &view_type!(Bar.{ 0 }), of which only `0` can be accessed+ --> $DIR/field-access.rs:43:14+ |+LL | let _ = &bar.1;+ | ^^^++error: field `c` cannot be accessed+ --> $DIR/field-access.rs:53:17+ |+LL | let _ = foo.c;+ | ^+ |+note: this expression has type &&view_type!(Foo.{ a, b }), of which only `a` and `b` can be accessed+ --> $DIR/field-access.rs:53:13+ |+LL | let _ = foo.c;+ | ^^^++error: field `2` cannot be accessed+ --> $DIR/field-access.rs:60:18+ |+LL | let _ = &bar.2;+ | ^+ |+note: this expression has type &&view_type!(Bar.{ 0, 1 }), of which only `0` and `1` can be accessed+ --> $DIR/field-access.rs:60:14+ |+LL | let _ = &bar.2;+ | ^^^++error: field `b` cannot be accessed+ --> $DIR/field-access.rs:71:17+ |+LL | let _ = baz.b;+ | ^+ |+note: this expression has type Baz, of which only `a` can be accessed+ --> $DIR/field-access.rs:71:13+ |+LL | let _ = baz.b;+ | ^^^++error: aborting due to 5 previous errors+tests/ui/view-types/field-access.rsadded76 + / 0 −
@@ -0,0 +1,76 @@+//@ revisions: legal illegal+//@[legal] check-pass++#![feature(view_types)]++use std::ops::Deref;+use std::view::view_type;++struct Foo {+ a: (),+ b: (),+ c: (),+}++struct Bar((), (), ());++struct Baz {}+struct Baz_ {+ a: (),+ b: (),+}++impl Deref for Baz {+ type Target = &'static view_type!(Baz_.{ a });++ fn deref(&self) -> &&'static view_type!(Baz_.{ a }) {+ todo!()+ }+}++// Basic access+fn f(foo: &view_type!(Foo.{ a }), bar: &view_type!(Bar.{ 0 })) {+ #[cfg(legal)]+ let _ = foo.a;+ #[cfg(illegal)]+ let _ = foo.b;+ //[illegal]~^ ERROR field `b` cannot be accessed+ //[illegal]~| NOTE this expression has type &view_type!(Foo.{ a }), of which only `a` can be accessed++ #[cfg(legal)]+ let _ = &bar.0;+ #[cfg(illegal)]+ let _ = &bar.1;+ //[illegal]~^ ERROR field `1` cannot be accessed+ //[illegal]~| NOTE this expression has type &view_type!(Bar.{ 0 }), of which only `0` can be accessed+}++// Works with multiple deref+fn g(foo: &&view_type!(Foo.{ a, b }), bar: &&view_type!(Bar.{ 0, 1 })) {+ #[cfg(legal)]+ let _ = foo.a;+ #[cfg(illegal)]+ let _ = foo.c;+ //[illegal]~^ ERROR field `c` cannot be accessed+ //[illegal]~| NOTE this expression has type &&view_type!(Foo.{ a, b }), of which only `a` and `b` can be accessed++ #[cfg(legal)]+ let _ = &bar.0;+ #[cfg(illegal)]+ let _ = &bar.2;+ //[illegal]~^ ERROR field `2` cannot be accessed+ //[illegal]~| NOTE this expression has type &&view_type!(Bar.{ 0, 1 }), of which only `0` and `1` can be accessed+}++// Works with manual deref implementation+fn h(baz: Baz) {+ #[cfg(legal)]+ let _ = baz.a;++ #[cfg(illegal)]+ let _ = baz.b;+ //[illegal]~^ ERROR field `b` cannot be accessed+ //[illegal]~| NOTE this expression has type Baz, of which only `a` can be accessed+}++fn main() {}