2020-08-19 19:07:03 +02:00
|
|
|
use crate::astconv::AstConv;
|
2023-03-09 20:42:45 +13:00
|
|
|
use crate::errors::{
|
|
|
|
|
AssocTypeBindingNotAllowed, ManualImplementation, MissingTypeParams,
|
|
|
|
|
ParenthesizedFnTraitExpansion,
|
|
|
|
|
};
|
2020-08-19 19:07:03 +02:00
|
|
|
use rustc_data_structures::fx::FxHashMap;
|
2022-12-08 13:31:21 +01:00
|
|
|
use rustc_errors::{pluralize, struct_span_err, Applicability, Diagnostic, ErrorGuaranteed};
|
2020-08-19 19:07:03 +02:00
|
|
|
use rustc_hir as hir;
|
|
|
|
|
use rustc_hir::def_id::DefId;
|
2023-02-17 18:42:08 +01:00
|
|
|
use rustc_infer::traits::FulfillmentError;
|
2023-03-09 20:42:45 +13:00
|
|
|
use rustc_middle::ty::TyCtxt;
|
2022-12-08 13:31:21 +01:00
|
|
|
use rustc_middle::ty::{self, Ty};
|
2020-08-19 19:07:03 +02:00
|
|
|
use rustc_session::parse::feature_err;
|
2023-02-19 04:03:56 +00:00
|
|
|
use rustc_span::edit_distance::find_best_match_for_name;
|
2020-08-19 19:07:03 +02:00
|
|
|
use rustc_span::symbol::{sym, Ident};
|
2022-07-25 22:40:00 +09:00
|
|
|
use rustc_span::{Span, Symbol, DUMMY_SP};
|
2020-08-19 19:07:03 +02:00
|
|
|
|
|
|
|
|
use std::collections::BTreeSet;
|
|
|
|
|
|
|
|
|
|
impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
|
|
|
|
|
/// On missing type parameters, emit an E0393 error and provide a structured suggestion using
|
|
|
|
|
/// the type parameter's name as a placeholder.
|
|
|
|
|
pub(crate) fn complain_about_missing_type_params(
|
|
|
|
|
&self,
|
2022-07-25 22:40:00 +09:00
|
|
|
missing_type_params: Vec<Symbol>,
|
2020-08-19 19:07:03 +02:00
|
|
|
def_id: DefId,
|
|
|
|
|
span: Span,
|
|
|
|
|
empty_generic_args: bool,
|
|
|
|
|
) {
|
|
|
|
|
if missing_type_params.is_empty() {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2022-05-07 07:32:01 +01:00
|
|
|
|
|
|
|
|
self.tcx().sess.emit_err(MissingTypeParams {
|
2020-08-19 19:07:03 +02:00
|
|
|
span,
|
2022-05-07 07:32:01 +01:00
|
|
|
def_span: self.tcx().def_span(def_id),
|
2022-09-05 17:26:57 -04:00
|
|
|
span_snippet: self.tcx().sess.source_map().span_to_snippet(span).ok(),
|
2022-05-07 07:32:01 +01:00
|
|
|
missing_type_params,
|
2020-08-19 19:07:03 +02:00
|
|
|
empty_generic_args,
|
2022-05-07 07:32:01 +01:00
|
|
|
});
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
|
|
|
|
|
/// an error and attempt to build a reasonable structured suggestion.
|
|
|
|
|
pub(crate) fn complain_about_internal_fn_trait(
|
|
|
|
|
&self,
|
|
|
|
|
span: Span,
|
|
|
|
|
trait_def_id: DefId,
|
2021-12-13 21:45:08 -04:00
|
|
|
trait_segment: &'_ hir::PathSegment<'_>,
|
2022-01-12 23:13:52 +01:00
|
|
|
is_impl: bool,
|
2020-08-19 19:07:03 +02:00
|
|
|
) {
|
2022-01-12 23:13:52 +01:00
|
|
|
if self.tcx().features().unboxed_closures {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-19 19:07:03 +02:00
|
|
|
let trait_def = self.tcx().trait_def(trait_def_id);
|
2022-01-12 23:13:52 +01:00
|
|
|
if !trait_def.paren_sugar {
|
2023-03-16 22:00:08 +00:00
|
|
|
if trait_segment.args().parenthesized == hir::GenericArgsParentheses::ParenSugar {
|
2022-01-12 23:13:52 +01:00
|
|
|
// For now, require that parenthetical notation be used only with `Fn()` etc.
|
|
|
|
|
let mut err = feature_err(
|
|
|
|
|
&self.tcx().sess.parse_sess,
|
|
|
|
|
sym::unboxed_closures,
|
|
|
|
|
span,
|
|
|
|
|
"parenthetical notation is only stable when used with `Fn`-family traits",
|
|
|
|
|
);
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let sess = self.tcx().sess;
|
2020-08-19 19:07:03 +02:00
|
|
|
|
2023-03-16 22:00:08 +00:00
|
|
|
if trait_segment.args().parenthesized != hir::GenericArgsParentheses::ParenSugar {
|
2020-08-19 19:07:03 +02:00
|
|
|
// For now, require that parenthetical notation be used only with `Fn()` etc.
|
2022-01-12 23:13:52 +01:00
|
|
|
let mut err = feature_err(
|
|
|
|
|
&sess.parse_sess,
|
|
|
|
|
sym::unboxed_closures,
|
|
|
|
|
span,
|
|
|
|
|
"the precise format of `Fn`-family traits' type parameters is subject to change",
|
|
|
|
|
);
|
|
|
|
|
// Do not suggest the other syntax if we are in trait impl:
|
2022-03-16 20:12:30 +08:00
|
|
|
// the desugaring would contain an associated type constraint.
|
2022-01-12 23:13:52 +01:00
|
|
|
if !is_impl {
|
|
|
|
|
err.span_suggestion(
|
|
|
|
|
span,
|
|
|
|
|
"use parenthetical notation instead",
|
2023-03-09 20:42:45 +13:00
|
|
|
fn_trait_to_string(self.tcx(), trait_segment, true),
|
2022-01-12 23:13:52 +01:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
2022-01-12 23:13:52 +01:00
|
|
|
|
|
|
|
|
if is_impl {
|
|
|
|
|
let trait_name = self.tcx().def_path_str(trait_def_id);
|
2022-05-07 07:50:01 +01:00
|
|
|
self.tcx().sess.emit_err(ManualImplementation { span, trait_name });
|
2022-01-12 23:13:52 +01:00
|
|
|
}
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(crate) fn complain_about_assoc_type_not_found<I>(
|
|
|
|
|
&self,
|
|
|
|
|
all_candidates: impl Fn() -> I,
|
|
|
|
|
ty_param_name: &str,
|
|
|
|
|
assoc_name: Ident,
|
|
|
|
|
span: Span,
|
2022-01-22 18:49:12 -06:00
|
|
|
) -> ErrorGuaranteed
|
|
|
|
|
where
|
2020-08-19 19:07:03 +02:00
|
|
|
I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
|
|
|
|
|
{
|
|
|
|
|
// The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
|
|
|
|
|
// valid span, so we point at the whole path segment instead.
|
|
|
|
|
let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
|
|
|
|
|
let mut err = struct_span_err!(
|
|
|
|
|
self.tcx().sess,
|
|
|
|
|
span,
|
|
|
|
|
E0220,
|
|
|
|
|
"associated type `{}` not found for `{}`",
|
|
|
|
|
assoc_name,
|
|
|
|
|
ty_param_name
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let all_candidate_names: Vec<_> = all_candidates()
|
2022-02-03 23:12:25 +01:00
|
|
|
.flat_map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
|
2023-06-23 18:18:05 -03:00
|
|
|
.filter_map(|item| {
|
|
|
|
|
if item.opt_rpitit_info.is_none() && item.kind == ty::AssocKind::Type {
|
|
|
|
|
Some(item.name)
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
})
|
2020-08-19 19:07:03 +02:00
|
|
|
.collect();
|
|
|
|
|
|
|
|
|
|
if let (Some(suggested_name), true) = (
|
Move lev_distance to rustc_ast, make non-generic
rustc_ast currently has a few dependencies on rustc_lexer. Ideally, an AST
would not have any dependency its lexer, for minimizing unnecessarily
design-time dependencies. Breaking this dependency would also have practical
benefits, since modifying rustc_lexer would not trigger a rebuild of rustc_ast.
This commit does not remove the rustc_ast --> rustc_lexer dependency,
but it does remove one of the sources of this dependency, which is the
code that handles fuzzy matching between symbol names for making suggestions
in diagnostics. Since that code depends only on Symbol, it is easy to move
it to rustc_span. It might even be best to move it to a separate crate,
since other tools such as Cargo use the same algorithm, and have simply
contain a duplicate of the code.
This changes the signature of find_best_match_for_name so that it is no
longer generic over its input. I checked the optimized binaries, and this
function was duplicated at nearly every call site, because most call sites
used short-lived iterator chains, generic over Map and such. But there's
no good reason for a function like this to be generic, since all it does
is immediately convert the generic input (the Iterator impl) to a concrete
Vec<Symbol>. This has all of the costs of generics (duplicated method bodies)
with no benefit.
Changing find_best_match_for_name to be non-generic removed about 10KB of
code from the optimized binary. I know it's a drop in the bucket, but we have
to start reducing binary size, and beginning to tame over-use of generics
is part of that.
2020-11-12 11:24:10 -08:00
|
|
|
find_best_match_for_name(&all_candidate_names, assoc_name.name, None),
|
2020-08-19 19:07:03 +02:00
|
|
|
assoc_name.span != DUMMY_SP,
|
|
|
|
|
) {
|
|
|
|
|
err.span_suggestion(
|
|
|
|
|
assoc_name.span,
|
|
|
|
|
"there is an associated type with a similar name",
|
2022-06-13 15:48:40 +09:00
|
|
|
suggested_name,
|
2020-08-19 19:07:03 +02:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
2022-07-11 06:53:01 +00:00
|
|
|
return err.emit();
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
|
2022-07-11 06:53:01 +00:00
|
|
|
// If we didn't find a good item in the supertraits (or couldn't get
|
|
|
|
|
// the supertraits), like in ItemCtxt, then look more generally from
|
|
|
|
|
// all visible traits. If there's one clear winner, just suggest that.
|
|
|
|
|
|
|
|
|
|
let visible_traits: Vec<_> = self
|
|
|
|
|
.tcx()
|
|
|
|
|
.all_traits()
|
|
|
|
|
.filter(|trait_def_id| {
|
|
|
|
|
let viz = self.tcx().visibility(*trait_def_id);
|
2022-10-31 16:19:36 +00:00
|
|
|
let def_id = self.item_def_id();
|
|
|
|
|
viz.is_accessible_from(def_id, self.tcx())
|
2022-07-11 06:53:01 +00:00
|
|
|
})
|
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
|
|
let wider_candidate_names: Vec<_> = visible_traits
|
|
|
|
|
.iter()
|
|
|
|
|
.flat_map(|trait_def_id| {
|
|
|
|
|
self.tcx().associated_items(*trait_def_id).in_definition_order()
|
|
|
|
|
})
|
2023-06-23 18:18:05 -03:00
|
|
|
.filter_map(|item| {
|
|
|
|
|
if item.opt_rpitit_info.is_none() && item.kind == ty::AssocKind::Type {
|
|
|
|
|
Some(item.name)
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
})
|
2022-07-11 06:53:01 +00:00
|
|
|
.collect();
|
|
|
|
|
|
|
|
|
|
if let (Some(suggested_name), true) = (
|
|
|
|
|
find_best_match_for_name(&wider_candidate_names, assoc_name.name, None),
|
|
|
|
|
assoc_name.span != DUMMY_SP,
|
|
|
|
|
) {
|
|
|
|
|
if let [best_trait] = visible_traits
|
|
|
|
|
.iter()
|
|
|
|
|
.filter(|trait_def_id| {
|
|
|
|
|
self.tcx()
|
|
|
|
|
.associated_items(*trait_def_id)
|
|
|
|
|
.filter_by_name_unhygienic(suggested_name)
|
|
|
|
|
.any(|item| item.kind == ty::AssocKind::Type)
|
|
|
|
|
})
|
|
|
|
|
.collect::<Vec<_>>()[..]
|
|
|
|
|
{
|
|
|
|
|
err.span_label(
|
|
|
|
|
assoc_name.span,
|
|
|
|
|
format!(
|
|
|
|
|
"there is a similarly named associated type `{suggested_name}` in the trait `{}`",
|
|
|
|
|
self.tcx().def_path_str(*best_trait)
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
return err.emit();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err.span_label(span, format!("associated type `{}` not found", assoc_name));
|
2022-01-22 18:49:12 -06:00
|
|
|
err.emit()
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
|
2023-02-17 17:06:27 +01:00
|
|
|
pub(crate) fn complain_about_ambiguous_inherent_assoc_type(
|
|
|
|
|
&self,
|
|
|
|
|
name: Ident,
|
2023-02-17 18:42:47 +01:00
|
|
|
candidates: Vec<DefId>,
|
2023-02-17 17:06:27 +01:00
|
|
|
span: Span,
|
|
|
|
|
) -> ErrorGuaranteed {
|
|
|
|
|
let mut err = struct_span_err!(
|
|
|
|
|
self.tcx().sess,
|
|
|
|
|
name.span,
|
|
|
|
|
E0034,
|
|
|
|
|
"multiple applicable items in scope"
|
|
|
|
|
);
|
|
|
|
|
err.span_label(name.span, format!("multiple `{name}` found"));
|
|
|
|
|
self.note_ambiguous_inherent_assoc_type(&mut err, candidates, span);
|
|
|
|
|
err.emit()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FIXME(fmease): Heavily adapted from `rustc_hir_typeck::method::suggest`. Deduplicate.
|
|
|
|
|
fn note_ambiguous_inherent_assoc_type(
|
|
|
|
|
&self,
|
|
|
|
|
err: &mut Diagnostic,
|
2023-02-17 18:42:47 +01:00
|
|
|
candidates: Vec<DefId>,
|
2023-02-17 17:06:27 +01:00
|
|
|
span: Span,
|
|
|
|
|
) {
|
|
|
|
|
let tcx = self.tcx();
|
|
|
|
|
|
|
|
|
|
// Dynamic limit to avoid hiding just one candidate, which is silly.
|
|
|
|
|
let limit = if candidates.len() == 5 { 5 } else { 4 };
|
|
|
|
|
|
2023-02-17 18:42:47 +01:00
|
|
|
for (index, &item) in candidates.iter().take(limit).enumerate() {
|
|
|
|
|
let impl_ = tcx.impl_of_method(item).unwrap();
|
2023-02-17 17:06:27 +01:00
|
|
|
|
2023-02-17 18:42:47 +01:00
|
|
|
let note_span = if item.is_local() {
|
|
|
|
|
Some(tcx.def_span(item))
|
2023-02-17 17:06:27 +01:00
|
|
|
} else if impl_.is_local() {
|
|
|
|
|
Some(tcx.def_span(impl_))
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let title = if candidates.len() > 1 {
|
|
|
|
|
format!("candidate #{}", index + 1)
|
|
|
|
|
} else {
|
|
|
|
|
"the candidate".into()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let impl_ty = tcx.at(span).type_of(impl_).subst_identity();
|
|
|
|
|
let note = format!("{title} is defined in an impl for the type `{impl_ty}`");
|
|
|
|
|
|
|
|
|
|
if let Some(span) = note_span {
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
err.span_note(span, note);
|
2023-02-17 17:06:27 +01:00
|
|
|
} else {
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
err.note(note);
|
2023-02-17 17:06:27 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if candidates.len() > limit {
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
err.note(format!("and {} others", candidates.len() - limit));
|
2023-02-17 17:06:27 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-08 13:31:21 +01:00
|
|
|
// FIXME(inherent_associated_types): Find similarly named associated types and suggest them.
|
|
|
|
|
pub(crate) fn complain_about_inherent_assoc_type_not_found(
|
|
|
|
|
&self,
|
|
|
|
|
name: Ident,
|
|
|
|
|
self_ty: Ty<'tcx>,
|
2023-02-17 18:42:08 +01:00
|
|
|
candidates: Vec<(DefId, (DefId, DefId))>,
|
|
|
|
|
fulfillment_errors: Vec<FulfillmentError<'tcx>>,
|
2022-12-08 13:31:21 +01:00
|
|
|
span: Span,
|
|
|
|
|
) -> ErrorGuaranteed {
|
2023-02-19 22:54:47 +01:00
|
|
|
// FIXME(fmease): This was copied in parts from an old version of `rustc_hir_typeck::method::suggest`.
|
|
|
|
|
// Either
|
|
|
|
|
// * update this code by applying changes similar to #106702 or by taking a
|
|
|
|
|
// Vec<(DefId, (DefId, DefId), Option<Vec<FulfillmentError<'tcx>>>)> or
|
|
|
|
|
// * deduplicate this code across the two crates.
|
|
|
|
|
|
2022-12-08 13:31:21 +01:00
|
|
|
let tcx = self.tcx();
|
|
|
|
|
|
|
|
|
|
let adt_did = self_ty.ty_adt_def().map(|def| def.did());
|
|
|
|
|
let add_def_label = |err: &mut Diagnostic| {
|
|
|
|
|
if let Some(did) = adt_did {
|
|
|
|
|
err.span_label(
|
|
|
|
|
tcx.def_span(did),
|
2023-02-21 14:05:32 -07:00
|
|
|
format!("associated item `{name}` not found for this {}", tcx.def_descr(did)),
|
2022-12-08 13:31:21 +01:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2023-02-17 18:42:08 +01:00
|
|
|
if fulfillment_errors.is_empty() {
|
2022-12-08 13:31:21 +01:00
|
|
|
// FIXME(fmease): Copied from `rustc_hir_typeck::method::probe`. Deduplicate.
|
|
|
|
|
|
|
|
|
|
let limit = if candidates.len() == 5 { 5 } else { 4 };
|
|
|
|
|
let type_candidates = candidates
|
|
|
|
|
.iter()
|
|
|
|
|
.take(limit)
|
2023-02-17 18:42:08 +01:00
|
|
|
.map(|&(impl_, _)| format!("- `{}`", tcx.at(span).type_of(impl_).subst_identity()))
|
2022-12-08 13:31:21 +01:00
|
|
|
.collect::<Vec<_>>()
|
|
|
|
|
.join("\n");
|
|
|
|
|
let additional_types = if candidates.len() > limit {
|
|
|
|
|
format!("\nand {} more types", candidates.len() - limit)
|
|
|
|
|
} else {
|
|
|
|
|
String::new()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let mut err = struct_span_err!(
|
|
|
|
|
tcx.sess,
|
|
|
|
|
name.span,
|
|
|
|
|
E0220,
|
|
|
|
|
"associated type `{name}` not found for `{self_ty}` in the current scope"
|
|
|
|
|
);
|
|
|
|
|
err.span_label(name.span, format!("associated item not found in `{self_ty}`"));
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
err.note(format!(
|
2022-12-08 13:31:21 +01:00
|
|
|
"the associated type was found for\n{type_candidates}{additional_types}",
|
|
|
|
|
));
|
|
|
|
|
add_def_label(&mut err);
|
|
|
|
|
return err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let mut bound_spans = Vec::new();
|
|
|
|
|
|
|
|
|
|
let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
|
|
|
|
|
let msg = format!(
|
|
|
|
|
"doesn't satisfy `{}`",
|
|
|
|
|
if obligation.len() > 50 { quiet } else { obligation }
|
|
|
|
|
);
|
|
|
|
|
match &self_ty.kind() {
|
|
|
|
|
// Point at the type that couldn't satisfy the bound.
|
|
|
|
|
ty::Adt(def, _) => bound_spans.push((tcx.def_span(def.did()), msg)),
|
|
|
|
|
// Point at the trait object that couldn't satisfy the bound.
|
|
|
|
|
ty::Dynamic(preds, _, _) => {
|
|
|
|
|
for pred in preds.iter() {
|
|
|
|
|
match pred.skip_binder() {
|
|
|
|
|
ty::ExistentialPredicate::Trait(tr) => {
|
|
|
|
|
bound_spans.push((tcx.def_span(tr.def_id), msg.clone()))
|
|
|
|
|
}
|
|
|
|
|
ty::ExistentialPredicate::Projection(_)
|
|
|
|
|
| ty::ExistentialPredicate::AutoTrait(_) => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// Point at the closure that couldn't satisfy the bound.
|
|
|
|
|
ty::Closure(def_id, _) => {
|
|
|
|
|
bound_spans.push((tcx.def_span(*def_id), format!("doesn't satisfy `{quiet}`")))
|
|
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let format_pred = |pred: ty::Predicate<'tcx>| {
|
|
|
|
|
let bound_predicate = pred.kind();
|
|
|
|
|
match bound_predicate.skip_binder() {
|
2023-06-16 05:59:42 +00:00
|
|
|
ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
|
2022-12-08 13:31:21 +01:00
|
|
|
let pred = bound_predicate.rebind(pred);
|
|
|
|
|
// `<Foo as Iterator>::Item = String`.
|
|
|
|
|
let projection_ty = pred.skip_binder().projection_ty;
|
|
|
|
|
|
2023-02-17 14:33:08 +11:00
|
|
|
let substs_with_infer_self = tcx.mk_substs_from_iter(
|
2023-07-05 20:13:26 +01:00
|
|
|
std::iter::once(Ty::new_var(tcx, ty::TyVid::from_u32(0)).into())
|
2022-12-08 13:31:21 +01:00
|
|
|
.chain(projection_ty.substs.iter().skip(1)),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let quiet_projection_ty =
|
|
|
|
|
tcx.mk_alias_ty(projection_ty.def_id, substs_with_infer_self);
|
|
|
|
|
|
|
|
|
|
let term = pred.skip_binder().term;
|
|
|
|
|
|
|
|
|
|
let obligation = format!("{projection_ty} = {term}");
|
|
|
|
|
let quiet = format!("{quiet_projection_ty} = {term}");
|
|
|
|
|
|
|
|
|
|
bound_span_label(projection_ty.self_ty(), &obligation, &quiet);
|
|
|
|
|
Some((obligation, projection_ty.self_ty()))
|
|
|
|
|
}
|
2023-06-16 05:59:42 +00:00
|
|
|
ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
|
2022-12-08 13:31:21 +01:00
|
|
|
let p = poly_trait_ref.trait_ref;
|
|
|
|
|
let self_ty = p.self_ty();
|
|
|
|
|
let path = p.print_only_trait_path();
|
|
|
|
|
let obligation = format!("{self_ty}: {path}");
|
|
|
|
|
let quiet = format!("_: {path}");
|
|
|
|
|
bound_span_label(self_ty, &obligation, &quiet);
|
|
|
|
|
Some((obligation, self_ty))
|
|
|
|
|
}
|
|
|
|
|
_ => None,
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// FIXME(fmease): `rustc_hir_typeck::method::suggest` uses a `skip_list` to filter out some bounds.
|
|
|
|
|
// I would do the same here if it didn't mean more code duplication.
|
2023-02-17 18:42:08 +01:00
|
|
|
let mut bounds: Vec<_> = fulfillment_errors
|
2022-12-08 13:31:21 +01:00
|
|
|
.into_iter()
|
2023-02-17 18:42:08 +01:00
|
|
|
.map(|error| error.root_obligation.predicate)
|
2022-12-08 13:31:21 +01:00
|
|
|
.filter_map(format_pred)
|
|
|
|
|
.map(|(p, _)| format!("`{}`", p))
|
|
|
|
|
.collect();
|
|
|
|
|
bounds.sort();
|
|
|
|
|
bounds.dedup();
|
|
|
|
|
|
|
|
|
|
let mut err = tcx.sess.struct_span_err(
|
|
|
|
|
name.span,
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
format!("the associated type `{name}` exists for `{self_ty}`, but its trait bounds were not satisfied")
|
2022-12-08 13:31:21 +01:00
|
|
|
);
|
|
|
|
|
if !bounds.is_empty() {
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
err.note(format!(
|
2022-12-08 13:31:21 +01:00
|
|
|
"the following trait bounds were not satisfied:\n{}",
|
|
|
|
|
bounds.join("\n")
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
err.span_label(
|
|
|
|
|
name.span,
|
|
|
|
|
format!("associated type cannot be referenced on `{self_ty}` due to unsatisfied trait bounds")
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
bound_spans.sort();
|
|
|
|
|
bound_spans.dedup();
|
|
|
|
|
for (span, msg) in bound_spans {
|
|
|
|
|
if !tcx.sess.source_map().is_span_accessible(span) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
err.span_label(span, msg);
|
2022-12-08 13:31:21 +01:00
|
|
|
}
|
|
|
|
|
add_def_label(&mut err);
|
|
|
|
|
err.emit()
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-19 19:07:03 +02:00
|
|
|
/// When there are any missing associated types, emit an E0191 error and attempt to supply a
|
|
|
|
|
/// reasonable suggestion on how to write it. For the case of multiple associated types in the
|
2021-10-02 07:21:01 +07:00
|
|
|
/// same trait bound have the same name (as they come from different supertraits), we instead
|
2020-08-19 19:07:03 +02:00
|
|
|
/// emit a generic note suggesting using a `where` clause to constraint instead.
|
|
|
|
|
pub(crate) fn complain_about_missing_associated_types(
|
|
|
|
|
&self,
|
|
|
|
|
associated_types: FxHashMap<Span, BTreeSet<DefId>>,
|
|
|
|
|
potential_assoc_types: Vec<Span>,
|
|
|
|
|
trait_bounds: &[hir::PolyTraitRef<'_>],
|
|
|
|
|
) {
|
|
|
|
|
if associated_types.values().all(|v| v.is_empty()) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
let tcx = self.tcx();
|
|
|
|
|
// FIXME: Marked `mut` so that we can replace the spans further below with a more
|
|
|
|
|
// appropriate one, but this should be handled earlier in the span assignment.
|
|
|
|
|
let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
|
|
|
|
|
.into_iter()
|
|
|
|
|
.map(|(span, def_ids)| {
|
|
|
|
|
(span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
|
|
|
|
|
})
|
|
|
|
|
.collect();
|
|
|
|
|
let mut names = vec![];
|
|
|
|
|
|
|
|
|
|
// Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
|
|
|
|
|
// `issue-22560.rs`.
|
|
|
|
|
let mut trait_bound_spans: Vec<Span> = vec![];
|
|
|
|
|
for (span, items) in &associated_types {
|
|
|
|
|
if !items.is_empty() {
|
|
|
|
|
trait_bound_spans.push(*span);
|
|
|
|
|
}
|
|
|
|
|
for assoc_item in items {
|
2022-03-13 00:52:25 +01:00
|
|
|
let trait_def_id = assoc_item.container_id(tcx);
|
2020-08-19 19:07:03 +02:00
|
|
|
names.push(format!(
|
|
|
|
|
"`{}` (from trait `{}`)",
|
2022-01-12 21:15:51 -05:00
|
|
|
assoc_item.name,
|
2020-08-19 19:07:03 +02:00
|
|
|
tcx.def_path_str(trait_def_id),
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
|
2021-02-16 00:30:06 +01:00
|
|
|
match bound.trait_ref.path.segments {
|
2020-08-19 19:07:03 +02:00
|
|
|
// FIXME: `trait_ref.path.span` can point to a full path with multiple
|
|
|
|
|
// segments, even though `trait_ref.path.segments` is of length `1`. Work
|
|
|
|
|
// around that bug here, even though it should be fixed elsewhere.
|
|
|
|
|
// This would otherwise cause an invalid suggestion. For an example, look at
|
2023-01-05 09:45:44 +01:00
|
|
|
// `tests/ui/issues/issue-28344.rs` where instead of the following:
|
2020-08-19 19:07:03 +02:00
|
|
|
//
|
|
|
|
|
// error[E0191]: the value of the associated type `Output`
|
|
|
|
|
// (from trait `std::ops::BitXor`) must be specified
|
|
|
|
|
// --> $DIR/issue-28344.rs:4:17
|
|
|
|
|
// |
|
|
|
|
|
// LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
|
|
|
|
|
// | ^^^^^^ help: specify the associated type:
|
|
|
|
|
// | `BitXor<Output = Type>`
|
|
|
|
|
//
|
|
|
|
|
// we would output:
|
|
|
|
|
//
|
|
|
|
|
// error[E0191]: the value of the associated type `Output`
|
|
|
|
|
// (from trait `std::ops::BitXor`) must be specified
|
|
|
|
|
// --> $DIR/issue-28344.rs:4:17
|
|
|
|
|
// |
|
|
|
|
|
// LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
|
|
|
|
|
// | ^^^^^^^^^^^^^ help: specify the associated type:
|
|
|
|
|
// | `BitXor::bitor<Output = Type>`
|
|
|
|
|
[segment] if segment.args.is_none() => {
|
|
|
|
|
trait_bound_spans = vec![segment.ident.span];
|
|
|
|
|
associated_types = associated_types
|
2023-04-01 23:44:16 +02:00
|
|
|
.into_values()
|
|
|
|
|
.map(|items| (segment.ident.span, items))
|
2020-08-19 19:07:03 +02:00
|
|
|
.collect();
|
|
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
names.sort();
|
|
|
|
|
trait_bound_spans.sort();
|
|
|
|
|
let mut err = struct_span_err!(
|
|
|
|
|
tcx.sess,
|
|
|
|
|
trait_bound_spans,
|
|
|
|
|
E0191,
|
|
|
|
|
"the value of the associated type{} {} must be specified",
|
|
|
|
|
pluralize!(names.len()),
|
|
|
|
|
names.join(", "),
|
|
|
|
|
);
|
|
|
|
|
let mut suggestions = vec![];
|
|
|
|
|
let mut types_count = 0;
|
|
|
|
|
let mut where_constraints = vec![];
|
2022-03-27 20:45:08 +02:00
|
|
|
let mut already_has_generics_args_suggestion = false;
|
2020-08-19 19:07:03 +02:00
|
|
|
for (span, assoc_items) in &associated_types {
|
|
|
|
|
let mut names: FxHashMap<_, usize> = FxHashMap::default();
|
|
|
|
|
for item in assoc_items {
|
|
|
|
|
types_count += 1;
|
2022-01-12 21:15:51 -05:00
|
|
|
*names.entry(item.name).or_insert(0) += 1;
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
let mut dupes = false;
|
|
|
|
|
for item in assoc_items {
|
2022-01-12 21:15:51 -05:00
|
|
|
let prefix = if names[&item.name] > 1 {
|
2022-03-13 00:52:25 +01:00
|
|
|
let trait_def_id = item.container_id(tcx);
|
2020-08-19 19:07:03 +02:00
|
|
|
dupes = true;
|
|
|
|
|
format!("{}::", tcx.def_path_str(trait_def_id))
|
|
|
|
|
} else {
|
|
|
|
|
String::new()
|
|
|
|
|
};
|
|
|
|
|
if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
|
2022-01-12 21:15:51 -05:00
|
|
|
err.span_label(sp, format!("`{}{}` defined here", prefix, item.name));
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if potential_assoc_types.len() == assoc_items.len() {
|
2022-03-27 20:45:08 +02:00
|
|
|
// When the amount of missing associated types equals the number of
|
2022-11-16 20:34:16 +00:00
|
|
|
// extra type arguments present. A suggesting to replace the generic args with
|
2022-03-27 20:45:08 +02:00
|
|
|
// associated types is already emitted.
|
|
|
|
|
already_has_generics_args_suggestion = true;
|
2020-08-19 19:07:03 +02:00
|
|
|
} else if let (Ok(snippet), false) =
|
|
|
|
|
(tcx.sess.source_map().span_to_snippet(*span), dupes)
|
|
|
|
|
{
|
|
|
|
|
let types: Vec<_> =
|
2022-01-12 21:15:51 -05:00
|
|
|
assoc_items.iter().map(|item| format!("{} = Type", item.name)).collect();
|
2020-08-19 19:07:03 +02:00
|
|
|
let code = if snippet.ends_with('>') {
|
|
|
|
|
// The user wrote `Trait<'a>` or similar and we don't have a type we can
|
|
|
|
|
// suggest, but at least we can clue them to the correct syntax
|
|
|
|
|
// `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
|
|
|
|
|
// suggestion.
|
|
|
|
|
format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
|
|
|
|
|
} else {
|
|
|
|
|
// The user wrote `Iterator`, so we don't have a type we can suggest, but at
|
|
|
|
|
// least we can clue them to the correct syntax `Iterator<Item = Type>`.
|
|
|
|
|
format!("{}<{}>", snippet, types.join(", "))
|
|
|
|
|
};
|
|
|
|
|
suggestions.push((*span, code));
|
|
|
|
|
} else if dupes {
|
|
|
|
|
where_constraints.push(*span);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
let where_msg = "consider introducing a new type parameter, adding `where` constraints \
|
|
|
|
|
using the fully-qualified path to the associated types";
|
|
|
|
|
if !where_constraints.is_empty() && suggestions.is_empty() {
|
|
|
|
|
// If there are duplicates associated type names and a single trait bound do not
|
2021-10-02 07:21:01 +07:00
|
|
|
// use structured suggestion, it means that there are multiple supertraits with
|
2020-08-19 19:07:03 +02:00
|
|
|
// the same associated type name.
|
|
|
|
|
err.help(where_msg);
|
|
|
|
|
}
|
2022-03-27 20:45:08 +02:00
|
|
|
if suggestions.len() != 1 || already_has_generics_args_suggestion {
|
2020-08-19 19:07:03 +02:00
|
|
|
// We don't need this label if there's an inline suggestion, show otherwise.
|
|
|
|
|
for (span, assoc_items) in &associated_types {
|
|
|
|
|
let mut names: FxHashMap<_, usize> = FxHashMap::default();
|
|
|
|
|
for item in assoc_items {
|
|
|
|
|
types_count += 1;
|
2022-01-12 21:15:51 -05:00
|
|
|
*names.entry(item.name).or_insert(0) += 1;
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
let mut label = vec![];
|
|
|
|
|
for item in assoc_items {
|
2022-01-12 21:15:51 -05:00
|
|
|
let postfix = if names[&item.name] > 1 {
|
2022-03-13 00:52:25 +01:00
|
|
|
let trait_def_id = item.container_id(tcx);
|
2020-08-19 19:07:03 +02:00
|
|
|
format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
|
|
|
|
|
} else {
|
|
|
|
|
String::new()
|
|
|
|
|
};
|
2022-01-12 21:15:51 -05:00
|
|
|
label.push(format!("`{}`{}", item.name, postfix));
|
2020-08-19 19:07:03 +02:00
|
|
|
}
|
|
|
|
|
if !label.is_empty() {
|
|
|
|
|
err.span_label(
|
|
|
|
|
*span,
|
|
|
|
|
format!(
|
|
|
|
|
"associated type{} {} must be specified",
|
|
|
|
|
pluralize!(label.len()),
|
|
|
|
|
label.join(", "),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if !suggestions.is_empty() {
|
|
|
|
|
err.multipart_suggestion(
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
format!("specify the associated type{}", pluralize!(types_count)),
|
2020-08-19 19:07:03 +02:00
|
|
|
suggestions,
|
|
|
|
|
Applicability::HasPlaceholders,
|
|
|
|
|
);
|
|
|
|
|
if !where_constraints.is_empty() {
|
|
|
|
|
err.span_help(where_constraints, where_msg);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-03-09 20:42:45 +13:00
|
|
|
|
|
|
|
|
/// Emits an error regarding forbidden type binding associations
|
|
|
|
|
pub fn prohibit_assoc_ty_binding(
|
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
|
span: Span,
|
|
|
|
|
segment: Option<(&hir::PathSegment<'_>, Span)>,
|
|
|
|
|
) {
|
2023-03-16 22:00:08 +00:00
|
|
|
tcx.sess.emit_err(AssocTypeBindingNotAllowed {
|
|
|
|
|
span,
|
|
|
|
|
fn_trait_expansion: if let Some((segment, span)) = segment
|
|
|
|
|
&& segment.args().parenthesized == hir::GenericArgsParentheses::ParenSugar
|
|
|
|
|
{
|
|
|
|
|
Some(ParenthesizedFnTraitExpansion {
|
|
|
|
|
span,
|
|
|
|
|
expanded_type: fn_trait_to_string(tcx, segment, false),
|
|
|
|
|
})
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
},
|
|
|
|
|
});
|
2023-03-09 20:42:45 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(crate) fn fn_trait_to_string(
|
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
|
trait_segment: &hir::PathSegment<'_>,
|
|
|
|
|
parenthesized: bool,
|
|
|
|
|
) -> String {
|
|
|
|
|
let args = trait_segment
|
|
|
|
|
.args
|
|
|
|
|
.as_ref()
|
|
|
|
|
.and_then(|args| args.args.get(0))
|
|
|
|
|
.and_then(|arg| match arg {
|
|
|
|
|
hir::GenericArg::Type(ty) => match ty.kind {
|
|
|
|
|
hir::TyKind::Tup(t) => t
|
|
|
|
|
.iter()
|
|
|
|
|
.map(|e| tcx.sess.source_map().span_to_snippet(e.span))
|
|
|
|
|
.collect::<Result<Vec<_>, _>>()
|
|
|
|
|
.map(|a| a.join(", ")),
|
|
|
|
|
_ => tcx.sess.source_map().span_to_snippet(ty.span),
|
|
|
|
|
}
|
|
|
|
|
.map(|s| {
|
|
|
|
|
// `s.empty()` checks to see if the type is the unit tuple, if so we don't want a comma
|
|
|
|
|
if parenthesized || s.is_empty() { format!("({})", s) } else { format!("({},)", s) }
|
|
|
|
|
})
|
|
|
|
|
.ok(),
|
|
|
|
|
_ => None,
|
|
|
|
|
})
|
|
|
|
|
.unwrap_or_else(|| "()".to_string());
|
|
|
|
|
|
|
|
|
|
let ret = trait_segment
|
|
|
|
|
.args()
|
|
|
|
|
.bindings
|
|
|
|
|
.iter()
|
|
|
|
|
.find_map(|b| match (b.ident.name == sym::Output, &b.kind) {
|
|
|
|
|
(true, hir::TypeBindingKind::Equality { term }) => {
|
|
|
|
|
let span = match term {
|
|
|
|
|
hir::Term::Ty(ty) => ty.span,
|
|
|
|
|
hir::Term::Const(c) => tcx.hir().span(c.hir_id),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
(span != tcx.hir().span(trait_segment.hir_id))
|
|
|
|
|
.then_some(tcx.sess.source_map().span_to_snippet(span).ok())
|
|
|
|
|
.flatten()
|
|
|
|
|
}
|
|
|
|
|
_ => None,
|
|
|
|
|
})
|
|
|
|
|
.unwrap_or_else(|| "()".to_string());
|
|
|
|
|
|
|
|
|
|
if parenthesized {
|
|
|
|
|
format!("{}{} -> {}", trait_segment.ident, args, ret)
|
|
|
|
|
} else {
|
|
|
|
|
format!("{}<{}, Output={}>", trait_segment.ident, args, ret)
|
|
|
|
|
}
|
|
|
|
|
}
|