1 use crate::astconv::AstConv;
2 use crate::errors::{ManualImplementation, MissingTypeParams};
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_errors::{pluralize, struct_span_err, Applicability, ErrorGuaranteed};
6 use rustc_hir::def_id::DefId;
8 use rustc_session::parse::feature_err;
9 use rustc_span::lev_distance::find_best_match_for_name;
10 use rustc_span::symbol::{sym, Ident};
11 use rustc_span::{Span, Symbol, DUMMY_SP};
13 use std::collections::BTreeSet;
15 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
16 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
17 /// the type parameter's name as a placeholder.
18 pub(crate) fn complain_about_missing_type_params(
20 missing_type_params: Vec<Symbol>,
23 empty_generic_args: bool,
25 if missing_type_params.is_empty() {
29 self.tcx().sess.emit_err(MissingTypeParams {
31 def_span: self.tcx().def_span(def_id),
32 span_snippet: self.tcx().sess.source_map().span_to_snippet(span).ok(),
38 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
39 /// an error and attempt to build a reasonable structured suggestion.
40 pub(crate) fn complain_about_internal_fn_trait(
44 trait_segment: &'_ hir::PathSegment<'_>,
47 if self.tcx().features().unboxed_closures {
51 let trait_def = self.tcx().trait_def(trait_def_id);
52 if !trait_def.paren_sugar {
53 if trait_segment.args().parenthesized {
54 // For now, require that parenthetical notation be used only with `Fn()` etc.
55 let mut err = feature_err(
56 &self.tcx().sess.parse_sess,
57 sym::unboxed_closures,
59 "parenthetical notation is only stable when used with `Fn`-family traits",
67 let sess = self.tcx().sess;
69 if !trait_segment.args().parenthesized {
70 // For now, require that parenthetical notation be used only with `Fn()` etc.
71 let mut err = feature_err(
73 sym::unboxed_closures,
75 "the precise format of `Fn`-family traits' type parameters is subject to change",
77 // Do not suggest the other syntax if we are in trait impl:
78 // the desugaring would contain an associated type constraint.
80 let args = trait_segment
83 .and_then(|args| args.args.get(0))
84 .and_then(|arg| match arg {
85 hir::GenericArg::Type(ty) => match ty.kind {
86 hir::TyKind::Tup(t) => t
88 .map(|e| sess.source_map().span_to_snippet(e.span))
89 .collect::<Result<Vec<_>, _>>()
90 .map(|a| a.join(", ")),
91 _ => sess.source_map().span_to_snippet(ty.span),
93 .map(|s| format!("({})", s))
97 .unwrap_or_else(|| "()".to_string());
98 let ret = trait_segment
102 .find_map(|b| match (b.ident.name == sym::Output, &b.kind) {
103 (true, hir::TypeBindingKind::Equality { term }) => {
104 let span = match term {
105 hir::Term::Ty(ty) => ty.span,
106 hir::Term::Const(c) => self.tcx().hir().span(c.hir_id),
108 sess.source_map().span_to_snippet(span).ok()
112 .unwrap_or_else(|| "()".to_string());
115 "use parenthetical notation instead",
116 format!("{}{} -> {}", trait_segment.ident, args, ret),
117 Applicability::MaybeIncorrect,
124 let trait_name = self.tcx().def_path_str(trait_def_id);
125 self.tcx().sess.emit_err(ManualImplementation { span, trait_name });
129 pub(crate) fn complain_about_assoc_type_not_found<I>(
131 all_candidates: impl Fn() -> I,
137 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
139 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
140 // valid span, so we point at the whole path segment instead.
141 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
142 let mut err = struct_span_err!(
146 "associated type `{}` not found for `{}`",
151 let all_candidate_names: Vec<_> = all_candidates()
152 .flat_map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
154 |item| if item.kind == ty::AssocKind::Type { Some(item.name) } else { None },
158 if let (Some(suggested_name), true) = (
159 find_best_match_for_name(&all_candidate_names, assoc_name.name, None),
160 assoc_name.span != DUMMY_SP,
164 "there is an associated type with a similar name",
166 Applicability::MaybeIncorrect,
171 // If we didn't find a good item in the supertraits (or couldn't get
172 // the supertraits), like in ItemCtxt, then look more generally from
173 // all visible traits. If there's one clear winner, just suggest that.
175 let visible_traits: Vec<_> = self
178 .filter(|trait_def_id| {
179 let viz = self.tcx().visibility(*trait_def_id);
180 let def_id = self.item_def_id();
181 viz.is_accessible_from(def_id, self.tcx())
185 let wider_candidate_names: Vec<_> = visible_traits
187 .flat_map(|trait_def_id| {
188 self.tcx().associated_items(*trait_def_id).in_definition_order()
191 |item| if item.kind == ty::AssocKind::Type { Some(item.name) } else { None },
195 if let (Some(suggested_name), true) = (
196 find_best_match_for_name(&wider_candidate_names, assoc_name.name, None),
197 assoc_name.span != DUMMY_SP,
199 if let [best_trait] = visible_traits
201 .filter(|trait_def_id| {
203 .associated_items(*trait_def_id)
204 .filter_by_name_unhygienic(suggested_name)
205 .any(|item| item.kind == ty::AssocKind::Type)
207 .collect::<Vec<_>>()[..]
212 "there is a similarly named associated type `{suggested_name}` in the trait `{}`",
213 self.tcx().def_path_str(*best_trait)
220 err.span_label(span, format!("associated type `{}` not found", assoc_name));
224 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
225 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
226 /// same trait bound have the same name (as they come from different supertraits), we instead
227 /// emit a generic note suggesting using a `where` clause to constraint instead.
228 pub(crate) fn complain_about_missing_associated_types(
230 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
231 potential_assoc_types: Vec<Span>,
232 trait_bounds: &[hir::PolyTraitRef<'_>],
234 if associated_types.values().all(|v| v.is_empty()) {
237 let tcx = self.tcx();
238 // FIXME: Marked `mut` so that we can replace the spans further below with a more
239 // appropriate one, but this should be handled earlier in the span assignment.
240 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
242 .map(|(span, def_ids)| {
243 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
246 let mut names = vec![];
248 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
250 let mut trait_bound_spans: Vec<Span> = vec![];
251 for (span, items) in &associated_types {
252 if !items.is_empty() {
253 trait_bound_spans.push(*span);
255 for assoc_item in items {
256 let trait_def_id = assoc_item.container_id(tcx);
258 "`{}` (from trait `{}`)",
260 tcx.def_path_str(trait_def_id),
264 if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
265 match bound.trait_ref.path.segments {
266 // FIXME: `trait_ref.path.span` can point to a full path with multiple
267 // segments, even though `trait_ref.path.segments` is of length `1`. Work
268 // around that bug here, even though it should be fixed elsewhere.
269 // This would otherwise cause an invalid suggestion. For an example, look at
270 // `tests/ui/issues/issue-28344.rs` where instead of the following:
272 // error[E0191]: the value of the associated type `Output`
273 // (from trait `std::ops::BitXor`) must be specified
274 // --> $DIR/issue-28344.rs:4:17
276 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
277 // | ^^^^^^ help: specify the associated type:
278 // | `BitXor<Output = Type>`
282 // error[E0191]: the value of the associated type `Output`
283 // (from trait `std::ops::BitXor`) must be specified
284 // --> $DIR/issue-28344.rs:4:17
286 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
287 // | ^^^^^^^^^^^^^ help: specify the associated type:
288 // | `BitXor::bitor<Output = Type>`
289 [segment] if segment.args.is_none() => {
290 trait_bound_spans = vec![segment.ident.span];
291 associated_types = associated_types
293 .map(|(_, items)| (segment.ident.span, items))
300 trait_bound_spans.sort();
301 let mut err = struct_span_err!(
305 "the value of the associated type{} {} must be specified",
306 pluralize!(names.len()),
309 let mut suggestions = vec![];
310 let mut types_count = 0;
311 let mut where_constraints = vec![];
312 let mut already_has_generics_args_suggestion = false;
313 for (span, assoc_items) in &associated_types {
314 let mut names: FxHashMap<_, usize> = FxHashMap::default();
315 for item in assoc_items {
317 *names.entry(item.name).or_insert(0) += 1;
319 let mut dupes = false;
320 for item in assoc_items {
321 let prefix = if names[&item.name] > 1 {
322 let trait_def_id = item.container_id(tcx);
324 format!("{}::", tcx.def_path_str(trait_def_id))
328 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
329 err.span_label(sp, format!("`{}{}` defined here", prefix, item.name));
332 if potential_assoc_types.len() == assoc_items.len() {
333 // When the amount of missing associated types equals the number of
334 // extra type arguments present. A suggesting to replace the generic args with
335 // associated types is already emitted.
336 already_has_generics_args_suggestion = true;
337 } else if let (Ok(snippet), false) =
338 (tcx.sess.source_map().span_to_snippet(*span), dupes)
341 assoc_items.iter().map(|item| format!("{} = Type", item.name)).collect();
342 let code = if snippet.ends_with('>') {
343 // The user wrote `Trait<'a>` or similar and we don't have a type we can
344 // suggest, but at least we can clue them to the correct syntax
345 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
347 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
349 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
350 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
351 format!("{}<{}>", snippet, types.join(", "))
353 suggestions.push((*span, code));
355 where_constraints.push(*span);
358 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
359 using the fully-qualified path to the associated types";
360 if !where_constraints.is_empty() && suggestions.is_empty() {
361 // If there are duplicates associated type names and a single trait bound do not
362 // use structured suggestion, it means that there are multiple supertraits with
363 // the same associated type name.
366 if suggestions.len() != 1 || already_has_generics_args_suggestion {
367 // We don't need this label if there's an inline suggestion, show otherwise.
368 for (span, assoc_items) in &associated_types {
369 let mut names: FxHashMap<_, usize> = FxHashMap::default();
370 for item in assoc_items {
372 *names.entry(item.name).or_insert(0) += 1;
374 let mut label = vec![];
375 for item in assoc_items {
376 let postfix = if names[&item.name] > 1 {
377 let trait_def_id = item.container_id(tcx);
378 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
382 label.push(format!("`{}`{}", item.name, postfix));
384 if !label.is_empty() {
388 "associated type{} {} must be specified",
389 pluralize!(label.len()),
396 if !suggestions.is_empty() {
397 err.multipart_suggestion(
398 &format!("specify the associated type{}", pluralize!(types_count)),
400 Applicability::HasPlaceholders,
402 if !where_constraints.is_empty() {
403 err.span_help(where_constraints, where_msg);