Skip to content

Suggest unwrapping ???<T> if a method cannot be found on it but is present on T. #102288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 28, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
240 changes: 174 additions & 66 deletions compiler/rustc_hir_analysis/src/check/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! found or is otherwise invalid.

use crate::check::FnCtxt;
use rustc_ast::ast::Mutability;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::{
pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
Expand Down Expand Up @@ -30,7 +31,7 @@ use rustc_trait_selection::traits::{
use std::cmp::Ordering;
use std::iter;

use super::probe::{IsSuggestion, Mode, ProbeScope};
use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope};
use super::{CandidateSource, MethodError, NoMatchData};

impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Expand Down Expand Up @@ -983,7 +984,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.check_for_field_method(&mut err, source, span, actual, item_name);
}

self.check_for_unwrap_self(&mut err, source, span, actual, item_name);
self.check_for_inner_self(&mut err, source, span, actual, item_name);

bound_spans.sort();
bound_spans.dedup();
Expand Down Expand Up @@ -1395,7 +1396,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

fn check_for_unwrap_self(
fn check_for_inner_self(
&self,
err: &mut Diagnostic,
source: SelfSource<'tcx>,
Expand All @@ -1408,81 +1409,188 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let call_expr = tcx.hir().expect_expr(tcx.hir().get_parent_node(expr.hir_id));

let ty::Adt(kind, substs) = actual.kind() else { return; };
if !kind.is_enum() {
return;
}
match kind.adt_kind() {
ty::AdtKind::Enum => {
let matching_variants: Vec<_> = kind
.variants()
.iter()
.flat_map(|variant| {
let [field] = &variant.fields[..] else { return None; };
let field_ty = field.ty(tcx, substs);

// Skip `_`, since that'll just lead to ambiguity.
if self.resolve_vars_if_possible(field_ty).is_ty_var() {
return None;
}

let matching_variants: Vec<_> = kind
.variants()
.iter()
.flat_map(|variant| {
let [field] = &variant.fields[..] else { return None; };
let field_ty = field.ty(tcx, substs);
self.lookup_probe(
span,
item_name,
field_ty,
call_expr,
ProbeScope::TraitsInScope,
)
.ok()
.map(|pick| (variant, field, pick))
})
.collect();

let ret_ty_matches = |diagnostic_item| {
if let Some(ret_ty) = self
.ret_coercion
.as_ref()
.map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
&& let ty::Adt(kind, _) = ret_ty.kind()
&& tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
{
true
} else {
false
}
};

// Skip `_`, since that'll just lead to ambiguity.
if self.resolve_vars_if_possible(field_ty).is_ty_var() {
return None;
match &matching_variants[..] {
[(_, field, pick)] => {
let self_ty = field.ty(tcx, substs);
err.span_note(
tcx.def_span(pick.item.def_id),
&format!("the method `{item_name}` exists on the type `{self_ty}`"),
);
let (article, kind, variant, question) =
if tcx.is_diagnostic_item(sym::Result, kind.did()) {
("a", "Result", "Err", ret_ty_matches(sym::Result))
} else if tcx.is_diagnostic_item(sym::Option, kind.did()) {
("an", "Option", "None", ret_ty_matches(sym::Option))
} else {
return;
};
if question {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use the `?` operator to extract the `{self_ty}` value, propagating \
{article} `{kind}::{variant}` value to the caller"
),
"?",
Applicability::MachineApplicable,
);
} else {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
panicking if the value is {article} `{kind}::{variant}`"
),
".expect(\"REASON\")",
Applicability::HasPlaceholders,
);
}
}
// FIXME(compiler-errors): Support suggestions for other matching enum variants
_ => {}
}

self.lookup_probe(span, item_name, field_ty, call_expr, ProbeScope::AllTraits)
.ok()
.map(|pick| (variant, field, pick))
})
.collect();

let ret_ty_matches = |diagnostic_item| {
if let Some(ret_ty) = self
.ret_coercion
.as_ref()
.map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
&& let ty::Adt(kind, _) = ret_ty.kind()
&& tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
{
true
} else {
false
}
};
// Target wrapper types - types that wrap or pretend to wrap another type,
// perhaps this inner type is meant to be called?
ty::AdtKind::Struct | ty::AdtKind::Union => {
let [first] = ***substs else { return; };
let ty::GenericArgKind::Type(ty) = first.unpack() else { return; };
let Ok(pick) = self.lookup_probe(
span,
item_name,
ty,
call_expr,
ProbeScope::TraitsInScope,
) else { return; };

match &matching_variants[..] {
[(_, field, pick)] => {
let self_ty = field.ty(tcx, substs);
err.span_note(
tcx.def_span(pick.item.def_id),
&format!("the method `{item_name}` exists on the type `{self_ty}`"),
);
let (article, kind, variant, question) =
if Some(kind.did()) == tcx.get_diagnostic_item(sym::Result) {
("a", "Result", "Err", ret_ty_matches(sym::Result))
} else if Some(kind.did()) == tcx.get_diagnostic_item(sym::Option) {
("an", "Option", "None", ret_ty_matches(sym::Option))
} else {
return;
};
if question {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use the `?` operator to extract the `{self_ty}` value, propagating \
{article} `{kind}::{variant}` value to the caller"
),
"?",
Applicability::MachineApplicable,
);
let name = self.ty_to_value_string(actual);
let inner_id = kind.did();
let mutable = if let Some(AutorefOrPtrAdjustment::Autoref { mutbl, .. }) =
pick.autoref_or_ptr_adjustment
{
Some(mutbl)
} else {
None
};

if tcx.is_diagnostic_item(sym::LocalKey, inner_id) {
err.help("use `with` or `try_with` to access thread local storage");
} else if Some(kind.did()) == tcx.lang_items().maybe_uninit() {
err.help(format!(
"if this `{name}` has been initialized, \
use one of the `assume_init` methods to access the inner value"
));
} else if tcx.is_diagnostic_item(sym::RefCell, inner_id) {
match mutable {
Some(Mutability::Not) => {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use `.borrow()` to borrow the `{ty}`, \
panicking if any outstanding mutable borrows exist."
),
".borrow()",
Applicability::MaybeIncorrect,
);
}
Some(Mutability::Mut) => {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use `.borrow_mut()` to mutably borrow the `{ty}`, \
panicking if any outstanding borrows exist."
),
".borrow_mut()",
Applicability::MaybeIncorrect,
);
}
Copy link
Member

@compiler-errors compiler-errors Sep 27, 2022

Choose a reason for hiding this comment

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

Perhaps deduplicate a bit?

Suggested change
Some(Mutability::Not) => {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use `.borrow()` to borrow the `{ty}`, \
panicking if any outstanding mutable borrows exist."
),
".borrow()",
Applicability::MaybeIncorrect,
);
}
Some(Mutability::Mut) => {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use `.borrow_mut()` to mutably borrow the `{ty}`, \
panicking if any outstanding borrows exist."
),
".borrow_mut()",
Applicability::MaybeIncorrect,
);
}
Some(mutbl) => {
let (suggestion, mutbly, mutbl) = match mutbl {
Mutability::Not => (".borrow()", "", "mutable "),
Mutability::Mut => (".borrow()", "mutably ", ""),
};
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use `.borrow()` to {mutbly}borrow the `{ty}`, \
panicking if any outstanding {mutbl}borrows exist."
),
suggestion,
Applicability::MaybeIncorrect,
);
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm I'm not sure. I prefer being too verbose rather than too clever, and this looks very clever 😄

Copy link
Member

Choose a reason for hiding this comment

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

This is a very common pattern to deduplicate essentially identical diagnostic messages. I'd actually prefer if you deduplicated it even more, but this one is the easiest to apply.

None => return,
}
} else if tcx.is_diagnostic_item(sym::Mutex, inner_id) {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
panicking if the value is {article} `{kind}::{variant}`"
"use `.lock()` to borrow the `{ty}`, \
blocking the current thread until it can be acquired"
),
".expect(\"REASON\")",
Applicability::HasPlaceholders,
".lock().unwrap()",
Applicability::MaybeIncorrect,
);
}
} else if tcx.is_diagnostic_item(sym::RwLock, inner_id) {
match mutable {
Some(Mutability::Not) => {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use `.read()` to borrow the `{ty}`, \
blocking the current thread until it can be acquired"
),
".read().unwrap()",
Applicability::MaybeIncorrect,
);
}
Some(Mutability::Mut) => {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"use `.write()` to mutably borrow the `{ty}`, \
blocking the current thread until it can be acquired"
),
".write().unwrap()",
Applicability::MaybeIncorrect,
);
}
None => return,
}
} else {
return;
};

err.span_note(
tcx.def_span(pick.item.def_id),
&format!("the method `{item_name}` exists on the type `{ty}`"),
);
}
// FIXME(compiler-errors): Support suggestions for other matching enum variants
_ => {}
}
}

Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ symbols! {
Left,
LinkedList,
LintPass,
LocalKey,
Mutex,
MutexGuard,
N,
Expand Down Expand Up @@ -266,6 +267,7 @@ symbols! {
Rc,
Ready,
Receiver,
RefCell,
Relaxed,
Release,
Result,
Expand All @@ -274,6 +276,7 @@ symbols! {
Rust,
RustcDecodable,
RustcEncodable,
RwLock,
RwLockReadGuard,
RwLockWriteGuard,
Send,
Expand Down
1 change: 1 addition & 0 deletions library/core/src/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,7 @@ impl<T, const N: usize> Cell<[T; N]> {
/// A mutable memory location with dynamically checked borrow rules
///
/// See the [module-level documentation](self) for more.
#[cfg_attr(not(test), rustc_diagnostic_item = "RefCell")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefCell<T: ?Sized> {
borrow: Cell<BorrowFlag>,
Expand Down
1 change: 1 addition & 0 deletions library/std/src/sync/rwlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ use crate::sys_common::rwlock as sys;
///
/// [`Mutex`]: super::Mutex
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "RwLock")]
pub struct RwLock<T: ?Sized> {
inner: sys::MovableRwLock,
poison: poison::Flag,
Expand Down
1 change: 1 addition & 0 deletions library/std/src/thread/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ use crate::fmt;
/// [loader lock]: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices
/// [`JoinHandle::join`]: crate::thread::JoinHandle::join
/// [`with`]: LocalKey::with
#[cfg_attr(not(test), rustc_diagnostic_item = "LocalKey")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct LocalKey<T: 'static> {
// This outer `LocalKey<T>` type is what's going to be stored in statics,
Expand Down
40 changes: 40 additions & 0 deletions src/test/ui/suggestions/inner_type.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// compile-flags: --edition=2021
// run-rustfix

pub struct Struct<T> {
pub p: T,
}

impl<T> Struct<T> {
pub fn method(&self) {}

pub fn some_mutable_method(&mut self) {}
}

fn main() {
let other_item = std::cell::RefCell::new(Struct { p: 42_u32 });

other_item.borrow().method();
//~^ ERROR no method named `method` found for struct `RefCell` in the current scope [E0599]
//~| HELP use `.borrow()` to borrow the `Struct<u32>`, panicking if any outstanding mutable borrows exist.

other_item.borrow_mut().some_mutable_method();
//~^ ERROR no method named `some_mutable_method` found for struct `RefCell` in the current scope [E0599]
//~| HELP use `.borrow_mut()` to mutably borrow the `Struct<u32>`, panicking if any outstanding borrows exist.

let another_item = std::sync::Mutex::new(Struct { p: 42_u32 });

another_item.lock().unwrap().method();
//~^ ERROR no method named `method` found for struct `Mutex` in the current scope [E0599]
//~| HELP use `.lock()` to borrow the `Struct<u32>`, blocking the current thread until it can be acquired

let another_item = std::sync::RwLock::new(Struct { p: 42_u32 });

another_item.read().unwrap().method();
//~^ ERROR no method named `method` found for struct `RwLock` in the current scope [E0599]
//~| HELP use `.read()` to borrow the `Struct<u32>`, blocking the current thread until it can be acquired

another_item.write().unwrap().some_mutable_method();
//~^ ERROR no method named `some_mutable_method` found for struct `RwLock` in the current scope [E0599]
//~| HELP use `.write()` to mutably borrow the `Struct<u32>`, blocking the current thread until it can be acquired
}
Loading