Skip to content
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
7 changes: 7 additions & 0 deletions compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1214,6 +1214,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
unsatisfied_predicates,
)
};
if let SelfSource::MethodCall(rcvr_expr) = source {
self.err_ctxt().note_field_shadowed_by_private_candidate(
&mut err,
rcvr_expr.hir_id,
self.param_env,
);
}

self.set_label_for_method_error(
&mut err,
Expand Down
27 changes: 27 additions & 0 deletions compiler/rustc_hir_typeck/src/op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
rhs_ty_var,
Some(lhs_expr),
|err, ty| {
self.err_ctxt().note_field_shadowed_by_private_candidate(
err,
rhs_expr.hir_id,
self.param_env,
);
if let Op::BinOp(binop) = op
&& binop.node == hir::BinOpKind::Eq
{
Expand Down Expand Up @@ -331,6 +336,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lhs_expr.span,
format!("cannot use `{}` on type `{}`", s, lhs_ty_str),
);
let err_ctxt = self.err_ctxt();
err_ctxt.note_field_shadowed_by_private_candidate(
&mut err,
lhs_expr.hir_id,
self.param_env,
);
err_ctxt.note_field_shadowed_by_private_candidate(
&mut err,
rhs_expr.hir_id,
self.param_env,
);
self.note_unmet_impls_on_type(&mut err, &errors, false);
(err, None)
}
Expand Down Expand Up @@ -391,6 +407,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_label(lhs_expr.span, lhs_ty_str.clone());
err.span_label(rhs_expr.span, rhs_ty_str);
}
let err_ctxt = self.err_ctxt();
err_ctxt.note_field_shadowed_by_private_candidate(
&mut err,
lhs_expr.hir_id,
self.param_env,
);
err_ctxt.note_field_shadowed_by_private_candidate(
&mut err,
rhs_expr.hir_id,
self.param_env,
);
let suggest_derive = self.can_eq(self.param_env, lhs_ty, rhs_ty);
self.note_unmet_impls_on_type(&mut err, &errors, suggest_derive);
(err, output_def_id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1528,6 +1528,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
label_or_note(span, terr.to_string(self.tcx));
}

if let Some(param_env) = param_env {
self.note_field_shadowed_by_private_candidate_in_cause(diag, cause, param_env);
}

if self.check_and_note_conflicting_crates(diag, terr) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
);
}

self.note_field_shadowed_by_private_candidate_in_cause(
&mut err,
&obligation.cause,
obligation.param_env,
);
self.try_to_add_help_message(
&root_obligation,
&obligation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ use rustc_hir::{
expr_needs_parens,
};
use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
use rustc_infer::traits::ImplSource;
use rustc_middle::middle::privacy::Level;
use rustc_middle::traits::IsConstable;
use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind};
use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::print::{
PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _,
Expand All @@ -49,7 +51,7 @@ use crate::error_reporting::TypeErrCtxt;
use crate::errors;
use crate::infer::InferCtxtExt as _;
use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt};
use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt, SelectionContext};

#[derive(Debug)]
pub enum CoroutineInteriorOrUpvar {
Expand Down Expand Up @@ -242,6 +244,213 @@ pub fn suggest_restriction<'tcx, G: EmissionGuarantee>(
}

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
pub fn note_field_shadowed_by_private_candidate_in_cause(
&self,
err: &mut Diag<'_>,
cause: &ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) {
let mut hir_ids = FxHashSet::default();
// Walk the parent chain so we can recover
// the source expression from whichever layer carries them.
let mut next_code = Some(cause.code());
while let Some(cause_code) = next_code {
match cause_code {
ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
hir_ids.insert(*lhs_hir_id);
hir_ids.insert(*rhs_hir_id);
}
ObligationCauseCode::FunctionArg { arg_hir_id, .. }
| ObligationCauseCode::ReturnValue(arg_hir_id)
| ObligationCauseCode::AwaitableExpr(arg_hir_id)
| ObligationCauseCode::BlockTailExpression(arg_hir_id, _)
| ObligationCauseCode::UnOp { hir_id: arg_hir_id } => {
hir_ids.insert(*arg_hir_id);
}
ObligationCauseCode::OpaqueReturnType(Some((_, hir_id))) => {
hir_ids.insert(*hir_id);
}
_ => {}
}
next_code = cause_code.parent();
}

if !cause.span.is_dummy()
&& let Some(body) = self.tcx.hir_maybe_body_owned_by(cause.body_id)
{
let mut expr_finder = FindExprBySpan::new(cause.span, self.tcx);
expr_finder.visit_body(body);
if let Some(expr) = expr_finder.result {
hir_ids.insert(expr.hir_id);
}
}

// we will sort immediately by source order before emitting any diagnostics
#[allow(rustc::potential_query_instability)]
let mut hir_ids: Vec<_> = hir_ids.into_iter().collect();
let source_map = self.tcx.sess.source_map();
hir_ids.sort_by_cached_key(|hir_id| {
let span = self.tcx.hir_span(*hir_id);
let lo = source_map.lookup_byte_offset(span.lo());
let hi = source_map.lookup_byte_offset(span.hi());
(lo.sf.name.prefer_remapped_unconditionally().to_string(), lo.pos.0, hi.pos.0)
});

for hir_id in hir_ids {
self.note_field_shadowed_by_private_candidate(err, hir_id, param_env);
}
}

pub fn note_field_shadowed_by_private_candidate(
&self,
err: &mut Diag<'_>,
hir_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
) {
let Some(typeck_results) = &self.typeck_results else {
return;
};
let Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
return;
};
let hir::ExprKind::Field(base_expr, field_ident) = expr.kind else {
return;
};

let Some(base_ty) = typeck_results.expr_ty_opt(base_expr) else {
return;
};
let base_ty = self.resolve_vars_if_possible(base_ty);
if base_ty.references_error() {
return;
}

let fn_body_hir_id = self.tcx.local_def_id_to_hir_id(typeck_results.hir_owner.def_id);
let mut private_candidate: Option<(Ty<'tcx>, Ty<'tcx>, Span)> = None;

for (deref_base_ty, _) in (self.autoderef_steps)(base_ty) {
let ty::Adt(base_def, args) = deref_base_ty.kind() else {
continue;
};

if base_def.is_enum() {
continue;
}

let (adjusted_ident, def_scope) =
self.tcx.adjust_ident_and_get_scope(field_ident, base_def.did(), fn_body_hir_id);

let Some((_, field_def)) =
base_def.non_enum_variant().fields.iter_enumerated().find(|(_, field)| {
field.ident(self.tcx).normalize_to_macros_2_0() == adjusted_ident
})
else {
continue;
};
let field_span = self
.tcx
.def_ident_span(field_def.did)
.unwrap_or_else(|| self.tcx.def_span(field_def.did));

if field_def.vis.is_accessible_from(def_scope, self.tcx) {
let accessible_field_ty = field_def.ty(self.tcx, args);
if let Some((private_base_ty, private_field_ty, private_field_span)) =
private_candidate
&& !self.can_eq(param_env, private_field_ty, accessible_field_ty)
{
let private_struct_span = match private_base_ty.kind() {
ty::Adt(private_base_def, _) => self
.tcx
.def_ident_span(private_base_def.did())
.unwrap_or_else(|| self.tcx.def_span(private_base_def.did())),
_ => DUMMY_SP,
};
let accessible_struct_span = self
.tcx
.def_ident_span(base_def.did())
.unwrap_or_else(|| self.tcx.def_span(base_def.did()));
let deref_impl_span = (typeck_results
.expr_adjustments(base_expr)
.iter()
.filter(|adj| {
matches!(adj.kind, Adjust::Deref(DerefAdjustKind::Overloaded(_)))
})
.count()
== 1)
.then(|| {
self.probe(|_| {
let deref_trait_did =
self.tcx.require_lang_item(LangItem::Deref, DUMMY_SP);
let trait_ref =
ty::TraitRef::new(self.tcx, deref_trait_did, [private_base_ty]);
let obligation: Obligation<'tcx, ty::Predicate<'tcx>> =
Obligation::new(
self.tcx,
ObligationCause::dummy(),
param_env,
trait_ref,
);
let Ok(Some(ImplSource::UserDefined(impl_data))) =
SelectionContext::new(self)
.select(&obligation.with(self.tcx, trait_ref))
else {
return None;
};
Some(self.tcx.def_span(impl_data.impl_def_id))
})
})
.flatten();

let mut note_spans: MultiSpan = private_struct_span.into();
if private_struct_span != DUMMY_SP {
note_spans.push_span_label(private_struct_span, "in this struct");
}
if private_field_span != DUMMY_SP {
note_spans.push_span_label(
private_field_span,
"if this field wasn't private, it would be accessible",
);
}
if accessible_struct_span != DUMMY_SP {
note_spans.push_span_label(
accessible_struct_span,
"this struct is accessible through auto-deref",
);
}
if field_span != DUMMY_SP {
note_spans
.push_span_label(field_span, "this is the field that was accessed");
}
if let Some(deref_impl_span) = deref_impl_span
&& deref_impl_span != DUMMY_SP
{
note_spans.push_span_label(
deref_impl_span,
"the field was accessed through this `Deref`",
);
}

err.span_note(
note_spans,
format!(
"there is a field `{field_ident}` on `{private_base_ty}` with type `{private_field_ty}` but it is private; `{field_ident}` from `{deref_base_ty}` was accessed through auto-deref instead"
),
);
}

// we finally get to the accessible field,
// so we can return early without checking the rest of the autoderef candidates
return;
}

private_candidate.get_or_insert((
deref_base_ty,
field_def.ty(self.tcx, args),
field_span,
));
}
}

pub fn suggest_restricting_param_bound(
&self,
err: &mut Diag<'_>,
Expand Down
Loading
Loading