1 //! Diagnostics related methods for `Ty`.
3 use crate::ty::subst::{GenericArg, GenericArgKind};
4 use crate::ty::TyKind::*;
6 ConstKind, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, InferTy,
7 ProjectionTy, Term, Ty, TyCtxt, TypeAndMut,
10 use rustc_errors::{Applicability, Diagnostic};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::{QPath, TyKind, WhereBoundPredicate, WherePredicate};
17 /// Similar to `Ty::is_primitive`, but also considers inferred numeric values to be primitive.
18 pub fn is_primitive_ty(self) -> bool {
28 | InferTy::FloatVar(_)
29 | InferTy::FreshIntTy(_)
30 | InferTy::FreshFloatTy(_)
35 /// Whether the type is succinctly representable as a type instead of just referred to with a
36 /// description in error messages. This is used in the main error message.
37 pub fn is_simple_ty(self) -> bool {
47 | InferTy::FloatVar(_)
48 | InferTy::FreshIntTy(_)
49 | InferTy::FreshFloatTy(_),
51 Ref(_, x, _) | Array(x, _) | Slice(x) => x.peel_refs().is_simple_ty(),
52 Tuple(tys) if tys.is_empty() => true,
57 /// Whether the type is succinctly representable as a type instead of just referred to with a
58 /// description in error messages. This is used in the primary span label. Beyond what
59 /// `is_simple_ty` includes, it also accepts ADTs with no type arguments and references to
60 /// ADTs with no type arguments.
61 pub fn is_simple_text(self) -> bool {
63 Adt(_, substs) => substs.non_erasable_generics().next().is_none(),
64 Ref(_, ty, _) => ty.is_simple_text(),
65 _ => self.is_simple_ty(),
69 /// Whether the type can be safely suggested during error recovery.
70 pub fn is_suggestable(self) -> bool {
71 fn generic_arg_is_suggestible(arg: GenericArg<'_>) -> bool {
73 GenericArgKind::Type(ty) => ty.is_suggestable(),
74 GenericArgKind::Const(c) => const_is_suggestable(c.val()),
79 fn const_is_suggestable(kind: ConstKind<'_>) -> bool {
82 | ConstKind::Bound(..)
83 | ConstKind::Placeholder(..)
84 | ConstKind::Error(..) => false,
89 // FIXME(compiler-errors): Some types are still not good to suggest,
90 // specifically references with lifetimes within the function. Not
91 //sure we have enough information to resolve whether a region is
92 // temporary, so I'll leave this as a fixme.
100 | GeneratorWitness(..)
104 Dynamic(dty, _) => dty.iter().all(|pred| match pred.skip_binder() {
105 ExistentialPredicate::Trait(ExistentialTraitRef { substs, .. }) => {
106 substs.iter().all(generic_arg_is_suggestible)
108 ExistentialPredicate::Projection(ExistentialProjection {
111 let term_is_suggestable = match term {
112 Term::Ty(ty) => ty.is_suggestable(),
113 Term::Const(c) => const_is_suggestable(c.val()),
115 term_is_suggestable && substs.iter().all(generic_arg_is_suggestible)
119 Projection(ProjectionTy { substs: args, .. }) | Adt(_, args) => {
120 args.iter().all(generic_arg_is_suggestible)
122 Tuple(args) => args.iter().all(|ty| ty.is_suggestable()),
123 Slice(ty) | RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => ty.is_suggestable(),
124 Array(ty, c) => ty.is_suggestable() && const_is_suggestable(c.val()),
130 pub fn suggest_arbitrary_trait_bound(
131 generics: &hir::Generics<'_>,
132 err: &mut Diagnostic,
136 let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
137 match (param, param_name) {
138 (Some(_), "Self") => return false,
141 // Suggest a where clause bound for a non-type paremeter.
142 let (action, prefix) = if generics.where_clause.predicates.is_empty() {
143 ("introducing a", " where ")
145 ("extending the", ", ")
147 err.span_suggestion_verbose(
148 generics.where_clause.tail_span_for_suggestion(),
150 "consider {} `where` bound, but there might be an alternative better way to express \
154 format!("{}{}: {}", prefix, param_name, constraint),
155 Applicability::MaybeIncorrect,
160 fn suggest_removing_unsized_bound(
161 generics: &hir::Generics<'_>,
162 err: &mut Diagnostic,
164 param: &hir::GenericParam<'_>,
165 def_id: Option<DefId>,
167 // See if there's a `?Sized` bound that can be removed to suggest that.
168 // First look at the `where` clause because we can have `where T: ?Sized`,
169 // then look at params.
170 for (where_pos, predicate) in generics.where_clause.predicates.iter().enumerate() {
172 WherePredicate::BoundPredicate(WhereBoundPredicate {
176 hir::TyKind::Path(hir::QPath::Resolved(
180 res: hir::def::Res::Def(hir::def::DefKind::TyParam, _),
189 }) if segment.ident.as_str() == param_name => {
190 for (pos, bound) in bounds.iter().enumerate() {
192 hir::GenericBound::Trait(poly, hir::TraitBoundModifier::Maybe)
193 if poly.trait_ref.trait_def_id() == def_id => {}
199 generics.where_clause.predicates.len(),
204 (1, _, 1, _) => generics.where_clause.span,
205 // where Foo: Bar, T: ?Sized,
207 (1, _, len, pos) if pos == len - 1 => generics.where_clause.predicates
212 // where T: ?Sized, Foo: Bar,
215 span.until(generics.where_clause.predicates[pos + 1].span())
217 // where T: ?Sized + Bar, Foo: Bar,
219 (_, 0, _, _) => bound.span().to(bounds[1].span().shrink_to_lo()),
220 // where T: Bar + ?Sized, Foo: Bar,
222 (_, pos, _, _) => bounds[pos - 1].span().shrink_to_hi().to(bound.span()),
224 err.span_suggestion_verbose(
226 "consider removing the `?Sized` bound to make the \
227 type parameter `Sized`",
229 Applicability::MaybeIncorrect,
236 for (pos, bound) in param.bounds.iter().enumerate() {
238 hir::GenericBound::Trait(poly, hir::TraitBoundModifier::Maybe)
239 if poly.trait_ref.trait_def_id() == def_id =>
241 let sp = match (param.bounds.len(), pos) {
244 (1, _) => param.span.shrink_to_hi().to(bound.span()),
247 (_, 0) => bound.span().to(param.bounds[1].span().shrink_to_lo()),
250 (_, pos) => param.bounds[pos - 1].span().shrink_to_hi().to(bound.span()),
252 err.span_suggestion_verbose(
254 "consider removing the `?Sized` bound to make the type parameter \
257 Applicability::MaybeIncorrect,
265 /// Suggest restricting a type param with a new bound.
266 pub fn suggest_constraining_type_param(
268 generics: &hir::Generics<'_>,
269 err: &mut Diagnostic,
272 def_id: Option<DefId>,
274 let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
276 let Some(param) = param else {
280 const MSG_RESTRICT_BOUND_FURTHER: &str = "consider further restricting this bound";
281 let msg_restrict_type = format!("consider restricting type parameter `{}`", param_name);
282 let msg_restrict_type_further =
283 format!("consider further restricting type parameter `{}`", param_name);
285 if def_id == tcx.lang_items().sized_trait() {
286 // Type parameters are already `Sized` by default.
287 err.span_label(param.span, &format!("this type parameter needs to be `{}`", constraint));
288 suggest_removing_unsized_bound(generics, err, param_name, param, def_id);
291 let mut suggest_restrict = |span| {
292 err.span_suggestion_verbose(
294 MSG_RESTRICT_BOUND_FURTHER,
295 format!(" + {}", constraint),
296 Applicability::MachineApplicable,
300 if param_name.starts_with("impl ") {
301 // If there's an `impl Trait` used in argument position, suggest
304 // fn foo(t: impl Foo) { ... }
307 // help: consider further restricting this bound with `+ Bar`
309 // Suggestion for tools in this case is:
311 // fn foo(t: impl Foo) { ... }
314 // replace with: `impl Foo + Bar`
316 suggest_restrict(param.span.shrink_to_hi());
320 if generics.where_clause.predicates.is_empty()
321 // Given `trait Base<T = String>: Super<T>` where `T: Copy`, suggest restricting in the
322 // `where` clause instead of `trait Base<T: Copy = String>: Super<T>`.
323 && !matches!(param.kind, hir::GenericParamKind::Type { default: Some(_), .. })
325 if let Some(span) = param.bounds_span_for_suggestions() {
326 // If user has provided some bounds, suggest restricting them:
328 // fn foo<T: Foo>(t: T) { ... }
331 // help: consider further restricting this bound with `+ Bar`
333 // Suggestion for tools in this case is:
335 // fn foo<T: Foo>(t: T) { ... }
338 // replace with: `T: Bar +`
339 suggest_restrict(span);
341 // If user hasn't provided any bounds, suggest adding a new one:
343 // fn foo<T>(t: T) { ... }
344 // - help: consider restricting this type parameter with `T: Foo`
345 err.span_suggestion_verbose(
346 param.span.shrink_to_hi(),
348 format!(": {}", constraint),
349 Applicability::MachineApplicable,
355 // This part is a bit tricky, because using the `where` clause user can
356 // provide zero, one or many bounds for the same type parameter, so we
357 // have following cases to consider:
359 // 1) When the type parameter has been provided zero bounds
362 // fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
363 // - help: consider restricting this type parameter with `where X: Bar`
366 // fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
367 // - insert: `, X: Bar`
370 // 2) When the type parameter has been provided one bound
373 // fn foo<T>(t: T) where T: Foo { ... }
376 // help: consider further restricting this bound with `+ Bar`
379 // fn foo<T>(t: T) where T: Foo { ... }
382 // replace with: `T: Bar +`
385 // 3) When the type parameter has been provided many bounds
388 // fn foo<T>(t: T) where T: Foo, T: Bar {... }
389 // - help: consider further restricting this type parameter with `where T: Zar`
392 // fn foo<T>(t: T) where T: Foo, T: Bar {... }
393 // - insert: `, T: Zar`
395 // Additionally, there may be no `where` clause whatsoever in the case that this was
396 // reached because the generic parameter has a default:
399 // trait Foo<T=()> {... }
400 // - help: consider further restricting this type parameter with `where T: Zar`
403 // trait Foo<T=()> where T: Zar {... }
404 // - insert: `where T: Zar`
406 if matches!(param.kind, hir::GenericParamKind::Type { default: Some(_), .. })
407 && generics.where_clause.predicates.len() == 0
409 // Suggest a bound, but there is no existing `where` clause *and* the type param has a
410 // default (`<T=Foo>`), so we suggest adding `where T: Bar`.
411 err.span_suggestion_verbose(
412 generics.where_clause.tail_span_for_suggestion(),
413 &msg_restrict_type_further,
414 format!(" where {}: {}", param_name, constraint),
415 Applicability::MachineApplicable,
418 let mut param_spans = Vec::new();
420 for predicate in generics.where_clause.predicates {
421 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
427 if let TyKind::Path(QPath::Resolved(_, path)) = &bounded_ty.kind {
428 if let Some(segment) = path.segments.first() {
429 if segment.ident.to_string() == param_name {
430 param_spans.push(span);
437 match param_spans[..] {
438 [¶m_span] => suggest_restrict(param_span.shrink_to_hi()),
440 err.span_suggestion_verbose(
441 generics.where_clause.tail_span_for_suggestion(),
442 &msg_restrict_type_further,
443 format!(", {}: {}", param_name, constraint),
444 Applicability::MachineApplicable,
454 /// Collect al types that have an implicit `'static` obligation that we could suggest `'_` for.
455 pub struct TraitObjectVisitor<'tcx>(pub Vec<&'tcx hir::Ty<'tcx>>, pub crate::hir::map::Map<'tcx>);
457 impl<'v> hir::intravisit::Visitor<'v> for TraitObjectVisitor<'v> {
458 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
460 hir::TyKind::TraitObject(
464 hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Static,
471 hir::TyKind::OpaqueDef(item_id, _) => {
473 let item = self.1.item(item_id);
474 hir::intravisit::walk_item(self, item);
478 hir::intravisit::walk_ty(self, ty);
482 /// Collect al types that have an implicit `'static` obligation that we could suggest `'_` for.
483 pub struct StaticLifetimeVisitor<'tcx>(pub Vec<Span>, pub crate::hir::map::Map<'tcx>);
485 impl<'v> hir::intravisit::Visitor<'v> for StaticLifetimeVisitor<'v> {
486 fn visit_lifetime(&mut self, lt: &'v hir::Lifetime) {
487 if let hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Static =
490 self.0.push(lt.span);