Skip to content

Rollup of 6 pull requests #105261

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 15 commits into from
Dec 4, 2022
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
1 change: 1 addition & 0 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,7 @@ pub enum StashKey {
/// Maybe there was a typo where a comma was forgotten before
/// FRU syntax
MaybeFruTypo,
CallAssocMethod,
}

fn default_track_diagnostic(_: &Diagnostic) {}
Expand Down
13 changes: 9 additions & 4 deletions compiler/rustc_hir_analysis/src/astconv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
assert!(self_ty.is_some());
}
} else {
assert!(self_ty.is_none() && parent_substs.is_empty());
assert!(self_ty.is_none());
}

let arg_count = Self::check_generic_arg_count(
Expand Down Expand Up @@ -1821,7 +1821,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {

// Check if we have an enum variant.
let mut variant_resolution = None;
if let ty::Adt(adt_def, _) = qself_ty.kind() {
if let ty::Adt(adt_def, adt_substs) = qself_ty.kind() {
if adt_def.is_enum() {
let variant_def = adt_def
.variants()
Expand Down Expand Up @@ -1923,8 +1923,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else {
continue;
};
// FIXME(inherent_associated_types): This does not substitute parameters.
let ty = tcx.type_of(assoc_ty_did);
let item_substs = self.create_substs_for_associated_item(
span,
assoc_ty_did,
assoc_segment,
adt_substs,
);
let ty = tcx.bound_type_of(assoc_ty_did).subst(tcx, item_substs);
return Ok((ty, DefKind::AssocTy, assoc_ty_did));
}
}
Expand Down
33 changes: 16 additions & 17 deletions compiler/rustc_hir_analysis/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1544,7 +1544,7 @@ fn check_fn_or_method<'tcx>(
check_where_clauses(wfcx, span, def_id);

check_return_position_impl_trait_in_trait_bounds(
tcx,
wfcx,
def_id,
sig.output(),
hir_decl.output.span(),
Expand Down Expand Up @@ -1580,13 +1580,14 @@ fn check_fn_or_method<'tcx>(

/// Basically `check_associated_type_bounds`, but separated for now and should be
/// deduplicated when RPITITs get lowered into real associated items.
#[tracing::instrument(level = "trace", skip(tcx))]
#[tracing::instrument(level = "trace", skip(wfcx))]
fn check_return_position_impl_trait_in_trait_bounds<'tcx>(
tcx: TyCtxt<'tcx>,
wfcx: &WfCheckingCtxt<'_, 'tcx>,
fn_def_id: LocalDefId,
fn_output: Ty<'tcx>,
span: Span,
) {
let tcx = wfcx.tcx();
if let Some(assoc_item) = tcx.opt_associated_item(fn_def_id.to_def_id())
&& assoc_item.container == ty::AssocItemContainer::TraitContainer
{
Expand All @@ -1596,22 +1597,20 @@ fn check_return_position_impl_trait_in_trait_bounds<'tcx>(
&& tcx.def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder
&& tcx.impl_trait_in_trait_parent(proj.item_def_id) == fn_def_id.to_def_id()
{
// Create a new context, since we want the opaque's ParamEnv and not the parent's.
let span = tcx.def_span(proj.item_def_id);
enter_wf_checking_ctxt(tcx, span, proj.item_def_id.expect_local(), |wfcx| {
let bounds = wfcx.tcx().explicit_item_bounds(proj.item_def_id);
let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
let normalized_bound = wfcx.normalize(span, None, bound);
traits::wf::predicate_obligations(
wfcx.infcx,
wfcx.param_env,
wfcx.body_id,
normalized_bound,
bound_span,
)
});
wfcx.register_obligations(wf_obligations);
let bounds = wfcx.tcx().explicit_item_bounds(proj.item_def_id);
let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
let bound = ty::EarlyBinder(bound).subst(tcx, proj.substs);
let normalized_bound = wfcx.normalize(span, None, bound);
traits::wf::predicate_obligations(
wfcx.infcx,
wfcx.param_env,
wfcx.body_id,
normalized_bound,
bound_span,
)
});
wfcx.register_obligations(wf_obligations);
}
}
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
let ty = match res {
Res::Err => {
self.suggest_assoc_method_call(segs);
let e =
self.tcx.sess.delay_span_bug(qpath.span(), "`Res::Err` but no error emitted");
self.set_tainted_by_errors(e);
Expand Down
64 changes: 61 additions & 3 deletions compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::errors;
use crate::FnCtxt;
use rustc_ast::ast::Mutability;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::StashKey;
use rustc_errors::{
pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
MultiSpan,
Expand All @@ -13,6 +14,8 @@ use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_hir::lang_items::LangItem;
use rustc_hir::PatKind::Binding;
use rustc_hir::PathSegment;
use rustc_hir::{ExprKind, Node, QPath};
use rustc_infer::infer::{
type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
Expand All @@ -35,11 +38,11 @@ use rustc_trait_selection::traits::{
FulfillmentError, Obligation, ObligationCause, ObligationCauseCode,
};

use std::cmp::Ordering;
use std::iter;

use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope};
use super::{CandidateSource, MethodError, NoMatchData};
use rustc_hir::intravisit::Visitor;
use std::cmp::Ordering;
use std::iter;

impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
Expand Down Expand Up @@ -1462,6 +1465,61 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
false
}

/// For code `rect::area(...)`,
/// if `rect` is a local variable and `area` is a valid assoc method for it,
/// we try to suggest `rect.area()`
pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) {
debug!("suggest_assoc_method_call segs: {:?}", segs);
let [seg1, seg2] = segs else { return; };
let Some(mut diag) =
self.tcx.sess.diagnostic().steal_diagnostic(seg1.ident.span, StashKey::CallAssocMethod)
else { return };

let map = self.infcx.tcx.hir();
let body = map.body(rustc_hir::BodyId { hir_id: self.body_id });
struct LetVisitor<'a> {
result: Option<&'a hir::Expr<'a>>,
ident_name: Symbol,
}

impl<'v> Visitor<'v> for LetVisitor<'v> {
fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
if let hir::StmtKind::Local(hir::Local { pat, init, .. }) = &ex.kind {
if let Binding(_, _, ident, ..) = pat.kind &&
ident.name == self.ident_name {
self.result = *init;
}
}
hir::intravisit::walk_stmt(self, ex);
}
}

let mut visitor = LetVisitor { result: None, ident_name: seg1.ident.name };
visitor.visit_body(&body);

let parent = self.tcx.hir().get_parent_node(seg1.hir_id);
if let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) &&
let Some(expr) = visitor.result {
let self_ty = self.node_ty(expr.hir_id);
let probe = self.lookup_probe(
seg2.ident,
self_ty,
call_expr,
ProbeScope::TraitsInScope,
);
if probe.is_ok() {
let sm = self.infcx.tcx.sess.source_map();
diag.span_suggestion_verbose(
sm.span_extend_while(seg1.ident.span.shrink_to_hi(), |c| c == ':').unwrap(),
"you may have meant to call an instance method",
".".to_string(),
Applicability::MaybeIncorrect
);
}
}
diag.emit();
}

/// Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()`
fn suggest_calling_method_on_field(
&self,
Expand Down
43 changes: 24 additions & 19 deletions compiler/rustc_parse/src/parser/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,22 @@ impl<'a> Parser<'a> {

Ok(Some(if self.token.is_keyword(kw::Let) {
self.parse_local_mk(lo, attrs, capture_semi, force_collect)?
} else if self.is_kw_followed_by_ident(kw::Mut) {
self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::MissingLet)?
} else if self.is_kw_followed_by_ident(kw::Auto) {
} else if self.is_kw_followed_by_ident(kw::Mut) && self.may_recover() {
self.recover_stmt_local_after_let(lo, attrs, InvalidVariableDeclarationSub::MissingLet)?
} else if self.is_kw_followed_by_ident(kw::Auto) && self.may_recover() {
self.bump(); // `auto`
self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::UseLetNotAuto)?
} else if self.is_kw_followed_by_ident(sym::var) {
self.recover_stmt_local_after_let(
lo,
attrs,
InvalidVariableDeclarationSub::UseLetNotAuto,
)?
} else if self.is_kw_followed_by_ident(sym::var) && self.may_recover() {
self.bump(); // `var`
self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::UseLetNotVar)?
self.recover_stmt_local_after_let(
lo,
attrs,
InvalidVariableDeclarationSub::UseLetNotVar,
)?
} else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() {
// We have avoided contextual keywords like `union`, items with `crate` visibility,
// or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something
Expand Down Expand Up @@ -213,13 +221,21 @@ impl<'a> Parser<'a> {
}
}

fn recover_stmt_local(
fn recover_stmt_local_after_let(
&mut self,
lo: Span,
attrs: AttrWrapper,
subdiagnostic: fn(Span) -> InvalidVariableDeclarationSub,
) -> PResult<'a, Stmt> {
let stmt = self.recover_local_after_let(lo, attrs)?;
let stmt =
self.collect_tokens_trailing_token(attrs, ForceCollect::Yes, |this, attrs| {
let local = this.parse_local(attrs)?;
// FIXME - maybe capture semicolon in recovery?
Ok((
this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
TrailingToken::None,
))
})?;
self.sess.emit_err(InvalidVariableDeclaration { span: lo, sub: subdiagnostic(lo) });
Ok(stmt)
}
Expand All @@ -243,17 +259,6 @@ impl<'a> Parser<'a> {
})
}

fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
let local = this.parse_local(attrs)?;
// FIXME - maybe capture semicolon in recovery?
Ok((
this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
TrailingToken::None,
))
})
}

/// Parses a local variable declaration.
fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
let lo = self.prev_token.span;
Expand Down
11 changes: 7 additions & 4 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1840,13 +1840,16 @@ impl<'a> Resolver<'a> {

(format!("use of undeclared type `{}`", ident), suggestion)
} else {
let suggestion = if ident.name == sym::alloc {
Some((
let mut suggestion = None;
if ident.name == sym::alloc {
suggestion = Some((
vec![],
String::from("add `extern crate alloc` to use the `alloc` crate"),
Applicability::MaybeIncorrect,
))
} else {
}

suggestion = suggestion.or_else(|| {
self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
|sugg| {
(
Expand All @@ -1856,7 +1859,7 @@ impl<'a> Resolver<'a> {
)
},
)
};
});
(format!("use of undeclared crate or module `{}`", ident), suggestion)
}
}
Expand Down
28 changes: 20 additions & 8 deletions compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3365,13 +3365,13 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
// Before we start looking for candidates, we have to get our hands
// on the type user is trying to perform invocation on; basically:
// we're transforming `HashMap::new` into just `HashMap`.
let path = match path.split_last() {
let prefix_path = match path.split_last() {
Some((_, path)) if !path.is_empty() => path,
_ => return Some(parent_err),
};

let (mut err, candidates) =
this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
this.smart_resolve_report_errors(prefix_path, path_span, PathSource::Type, None);

// There are two different error messages user might receive at
// this point:
Expand Down Expand Up @@ -3415,11 +3415,23 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {

if this.should_report_errs() {
if candidates.is_empty() {
// When there is no suggested imports, we can just emit the error
// and suggestions immediately. Note that we bypass the usually error
// reporting routine (ie via `self.r.report_error`) because we need
// to post-process the `ResolutionError` above.
err.emit();
if path.len() == 2 && prefix_path.len() == 1 {
// Delay to check whether methond name is an associated function or not
// ```
// let foo = Foo {};
// foo::bar(); // possibly suggest to foo.bar();
//```
err.stash(
prefix_path[0].ident.span,
rustc_errors::StashKey::CallAssocMethod,
);
} else {
// When there is no suggested imports, we can just emit the error
// and suggestions immediately. Note that we bypass the usually error
// reporting routine (ie via `self.r.report_error`) because we need
// to post-process the `ResolutionError` above.
err.emit();
}
} else {
// If there are suggested imports, the error reporting is delayed
this.r.use_injections.push(UseError {
Expand All @@ -3428,7 +3440,7 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
def_id,
instead: false,
suggestion: None,
path: path.into(),
path: prefix_path.into(),
is_call: source.is_call(),
});
}
Expand Down
Loading