1 use crate::astconv::AstConv;
2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_errors::{pluralize, struct_span_err, Applicability, ErrorGuaranteed};
5 use rustc_hir::def_id::DefId;
7 use rustc_session::parse::feature_err;
8 use rustc_span::lev_distance::find_best_match_for_name;
9 use rustc_span::symbol::{sym, Ident};
10 use rustc_span::{Span, DUMMY_SP};
12 use std::collections::BTreeSet;
14 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
15 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
16 /// the type parameter's name as a placeholder.
17 pub(crate) fn complain_about_missing_type_params(
19 missing_type_params: Vec<String>,
22 empty_generic_args: bool,
24 if missing_type_params.is_empty() {
28 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
29 let mut err = struct_span_err!(
33 "the type parameter{} {} must be explicitly specified",
34 pluralize!(missing_type_params.len()),
38 self.tcx().def_span(def_id),
40 "type parameter{} {} must be specified for this",
41 pluralize!(missing_type_params.len()),
45 let mut suggested = false;
46 if let (Ok(snippet), true) = (
47 self.tcx().sess.source_map().span_to_snippet(span),
48 // Don't suggest setting the type params if there are some already: the order is
49 // tricky to get right and the user will already know what the syntax is.
52 if snippet.ends_with('>') {
53 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
54 // we would have to preserve the right order. For now, as clearly the user is
55 // aware of the syntax, we do nothing.
57 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
58 // least we can clue them to the correct syntax `Iterator<Type>`.
62 "set the type parameter{plural} to the desired type{plural}",
63 plural = pluralize!(missing_type_params.len()),
65 format!("{}<{}>", snippet, missing_type_params.join(", ")),
66 Applicability::HasPlaceholders,
75 "missing reference{} to {}",
76 pluralize!(missing_type_params.len()),
82 "because of the default `Self` reference, type parameters must be \
83 specified on object types",
88 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
89 /// an error and attempt to build a reasonable structured suggestion.
90 pub(crate) fn complain_about_internal_fn_trait(
94 trait_segment: &'_ hir::PathSegment<'_>,
97 if self.tcx().features().unboxed_closures {
101 let trait_def = self.tcx().trait_def(trait_def_id);
102 if !trait_def.paren_sugar {
103 if trait_segment.args().parenthesized {
104 // For now, require that parenthetical notation be used only with `Fn()` etc.
105 let mut err = feature_err(
106 &self.tcx().sess.parse_sess,
107 sym::unboxed_closures,
109 "parenthetical notation is only stable when used with `Fn`-family traits",
117 let sess = self.tcx().sess;
119 if !trait_segment.args().parenthesized {
120 // For now, require that parenthetical notation be used only with `Fn()` etc.
121 let mut err = feature_err(
123 sym::unboxed_closures,
125 "the precise format of `Fn`-family traits' type parameters is subject to change",
127 // Do not suggest the other syntax if we are in trait impl:
128 // the desugaring would contain an associated type constraint.
130 let args = trait_segment
133 .and_then(|args| args.args.get(0))
134 .and_then(|arg| match arg {
135 hir::GenericArg::Type(ty) => match ty.kind {
136 hir::TyKind::Tup(t) => t
138 .map(|e| sess.source_map().span_to_snippet(e.span))
139 .collect::<Result<Vec<_>, _>>()
140 .map(|a| a.join(", ")),
141 _ => sess.source_map().span_to_snippet(ty.span),
143 .map(|s| format!("({})", s))
147 .unwrap_or_else(|| "()".to_string());
148 let ret = trait_segment
152 .find_map(|b| match (b.ident.name == sym::Output, &b.kind) {
153 (true, hir::TypeBindingKind::Equality { term }) => {
154 let span = match term {
155 hir::Term::Ty(ty) => ty.span,
156 hir::Term::Const(c) => self.tcx().hir().span(c.hir_id),
158 sess.source_map().span_to_snippet(span).ok()
162 .unwrap_or_else(|| "()".to_string());
165 "use parenthetical notation instead",
166 format!("{}{} -> {}", trait_segment.ident, args, ret),
167 Applicability::MaybeIncorrect,
174 let trait_name = self.tcx().def_path_str(trait_def_id);
179 "manual implementations of `{}` are experimental",
184 format!("manual implementations of `{}` are experimental", trait_name),
186 .help("add `#![feature(unboxed_closures)]` to the crate attributes to enable")
191 pub(crate) fn complain_about_assoc_type_not_found<I>(
193 all_candidates: impl Fn() -> I,
199 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
201 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
202 // valid span, so we point at the whole path segment instead.
203 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
204 let mut err = struct_span_err!(
208 "associated type `{}` not found for `{}`",
213 let all_candidate_names: Vec<_> = all_candidates()
214 .flat_map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
216 |item| if item.kind == ty::AssocKind::Type { Some(item.name) } else { None },
220 if let (Some(suggested_name), true) = (
221 find_best_match_for_name(&all_candidate_names, assoc_name.name, None),
222 assoc_name.span != DUMMY_SP,
226 "there is an associated type with a similar name",
227 suggested_name.to_string(),
228 Applicability::MaybeIncorrect,
231 err.span_label(span, format!("associated type `{}` not found", assoc_name));
237 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
238 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
239 /// same trait bound have the same name (as they come from different supertraits), we instead
240 /// emit a generic note suggesting using a `where` clause to constraint instead.
241 pub(crate) fn complain_about_missing_associated_types(
243 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
244 potential_assoc_types: Vec<Span>,
245 trait_bounds: &[hir::PolyTraitRef<'_>],
247 if associated_types.values().all(|v| v.is_empty()) {
250 let tcx = self.tcx();
251 // FIXME: Marked `mut` so that we can replace the spans further below with a more
252 // appropriate one, but this should be handled earlier in the span assignment.
253 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
255 .map(|(span, def_ids)| {
256 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
259 let mut names = vec![];
261 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
263 let mut trait_bound_spans: Vec<Span> = vec![];
264 for (span, items) in &associated_types {
265 if !items.is_empty() {
266 trait_bound_spans.push(*span);
268 for assoc_item in items {
269 let trait_def_id = assoc_item.container.id();
271 "`{}` (from trait `{}`)",
273 tcx.def_path_str(trait_def_id),
277 if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
278 match bound.trait_ref.path.segments {
279 // FIXME: `trait_ref.path.span` can point to a full path with multiple
280 // segments, even though `trait_ref.path.segments` is of length `1`. Work
281 // around that bug here, even though it should be fixed elsewhere.
282 // This would otherwise cause an invalid suggestion. For an example, look at
283 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
285 // error[E0191]: the value of the associated type `Output`
286 // (from trait `std::ops::BitXor`) must be specified
287 // --> $DIR/issue-28344.rs:4:17
289 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
290 // | ^^^^^^ help: specify the associated type:
291 // | `BitXor<Output = Type>`
295 // error[E0191]: the value of the associated type `Output`
296 // (from trait `std::ops::BitXor`) must be specified
297 // --> $DIR/issue-28344.rs:4:17
299 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
300 // | ^^^^^^^^^^^^^ help: specify the associated type:
301 // | `BitXor::bitor<Output = Type>`
302 [segment] if segment.args.is_none() => {
303 trait_bound_spans = vec![segment.ident.span];
304 associated_types = associated_types
306 .map(|(_, items)| (segment.ident.span, items))
313 trait_bound_spans.sort();
314 let mut err = struct_span_err!(
318 "the value of the associated type{} {} must be specified",
319 pluralize!(names.len()),
322 let mut suggestions = vec![];
323 let mut types_count = 0;
324 let mut where_constraints = vec![];
325 let mut already_has_generics_args_suggestion = false;
326 for (span, assoc_items) in &associated_types {
327 let mut names: FxHashMap<_, usize> = FxHashMap::default();
328 for item in assoc_items {
330 *names.entry(item.name).or_insert(0) += 1;
332 let mut dupes = false;
333 for item in assoc_items {
334 let prefix = if names[&item.name] > 1 {
335 let trait_def_id = item.container.id();
337 format!("{}::", tcx.def_path_str(trait_def_id))
341 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
342 err.span_label(sp, format!("`{}{}` defined here", prefix, item.name));
345 if potential_assoc_types.len() == assoc_items.len() {
346 // When the amount of missing associated types equals the number of
347 // extra type arguments present. A suggesting to replace the generic args with
348 // associated types is already emitted.
349 already_has_generics_args_suggestion = true;
350 } else if let (Ok(snippet), false) =
351 (tcx.sess.source_map().span_to_snippet(*span), dupes)
354 assoc_items.iter().map(|item| format!("{} = Type", item.name)).collect();
355 let code = if snippet.ends_with('>') {
356 // The user wrote `Trait<'a>` or similar and we don't have a type we can
357 // suggest, but at least we can clue them to the correct syntax
358 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
360 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
362 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
363 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
364 format!("{}<{}>", snippet, types.join(", "))
366 suggestions.push((*span, code));
368 where_constraints.push(*span);
371 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
372 using the fully-qualified path to the associated types";
373 if !where_constraints.is_empty() && suggestions.is_empty() {
374 // If there are duplicates associated type names and a single trait bound do not
375 // use structured suggestion, it means that there are multiple supertraits with
376 // the same associated type name.
379 if suggestions.len() != 1 || already_has_generics_args_suggestion {
380 // We don't need this label if there's an inline suggestion, show otherwise.
381 for (span, assoc_items) in &associated_types {
382 let mut names: FxHashMap<_, usize> = FxHashMap::default();
383 for item in assoc_items {
385 *names.entry(item.name).or_insert(0) += 1;
387 let mut label = vec![];
388 for item in assoc_items {
389 let postfix = if names[&item.name] > 1 {
390 let trait_def_id = item.container.id();
391 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
395 label.push(format!("`{}`{}", item.name, postfix));
397 if !label.is_empty() {
401 "associated type{} {} must be specified",
402 pluralize!(label.len()),
409 if !suggestions.is_empty() {
410 err.multipart_suggestion(
411 &format!("specify the associated type{}", pluralize!(types_count)),
413 Applicability::HasPlaceholders,
415 if !where_constraints.is_empty() {
416 err.span_help(where_constraints, where_msg);