1 //! Diagnostics related methods for `TyS`.
3 use crate::ty::subst::{GenericArg, GenericArgKind};
4 use crate::ty::TyKind::*;
6 ConstKind, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, InferTy,
7 ProjectionTy, TyCtxt, TyS, TypeAndMut,
10 use rustc_errors::{Applicability, DiagnosticBuilder};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::{QPath, TyKind, WhereBoundPredicate, WherePredicate};
16 impl<'tcx> TyS<'tcx> {
17 /// Similar to `TyS::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 { substs, ty, .. }) => {
109 ty.is_suggestable() && substs.iter().all(generic_arg_is_suggestible)
113 Projection(ProjectionTy { substs: args, .. }) | Adt(_, args) | Tuple(args) => {
114 args.iter().all(generic_arg_is_suggestible)
116 Slice(ty) | RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => ty.is_suggestable(),
117 Array(ty, c) => ty.is_suggestable() && const_is_suggestable(c.val),
123 pub fn suggest_arbitrary_trait_bound(
124 generics: &hir::Generics<'_>,
125 err: &mut DiagnosticBuilder<'_>,
129 let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
130 match (param, param_name) {
131 (Some(_), "Self") => return false,
134 // Suggest a where clause bound for a non-type paremeter.
135 let (action, prefix) = if generics.where_clause.predicates.is_empty() {
136 ("introducing a", " where ")
138 ("extending the", ", ")
140 err.span_suggestion_verbose(
141 generics.where_clause.tail_span_for_suggestion(),
143 "consider {} `where` bound, but there might be an alternative better way to express \
147 format!("{}{}: {}", prefix, param_name, constraint),
148 Applicability::MaybeIncorrect,
153 fn suggest_removing_unsized_bound(
154 generics: &hir::Generics<'_>,
155 err: &mut DiagnosticBuilder<'_>,
157 param: &hir::GenericParam<'_>,
158 def_id: Option<DefId>,
160 // See if there's a `?Sized` bound that can be removed to suggest that.
161 // First look at the `where` clause because we can have `where T: ?Sized`,
162 // then look at params.
163 for (where_pos, predicate) in generics.where_clause.predicates.iter().enumerate() {
165 WherePredicate::BoundPredicate(WhereBoundPredicate {
169 hir::TyKind::Path(hir::QPath::Resolved(
173 res: hir::def::Res::Def(hir::def::DefKind::TyParam, _),
182 }) if segment.ident.as_str() == param_name => {
183 for (pos, bound) in bounds.iter().enumerate() {
185 hir::GenericBound::Trait(poly, hir::TraitBoundModifier::Maybe)
186 if poly.trait_ref.trait_def_id() == def_id => {}
192 generics.where_clause.predicates.len(),
197 (1, _, 1, _) => generics.where_clause.span,
198 // where Foo: Bar, T: ?Sized,
200 (1, _, len, pos) if pos == len - 1 => generics.where_clause.predicates
205 // where T: ?Sized, Foo: Bar,
208 span.until(generics.where_clause.predicates[pos + 1].span())
210 // where T: ?Sized + Bar, Foo: Bar,
212 (_, 0, _, _) => bound.span().to(bounds[1].span().shrink_to_lo()),
213 // where T: Bar + ?Sized, Foo: Bar,
215 (_, pos, _, _) => bounds[pos - 1].span().shrink_to_hi().to(bound.span()),
217 err.span_suggestion_verbose(
219 "consider removing the `?Sized` bound to make the \
220 type parameter `Sized`",
222 Applicability::MaybeIncorrect,
229 for (pos, bound) in param.bounds.iter().enumerate() {
231 hir::GenericBound::Trait(poly, hir::TraitBoundModifier::Maybe)
232 if poly.trait_ref.trait_def_id() == def_id =>
234 let sp = match (param.bounds.len(), pos) {
237 (1, _) => param.span.shrink_to_hi().to(bound.span()),
240 (_, 0) => bound.span().to(param.bounds[1].span().shrink_to_lo()),
243 (_, pos) => param.bounds[pos - 1].span().shrink_to_hi().to(bound.span()),
245 err.span_suggestion_verbose(
247 "consider removing the `?Sized` bound to make the type parameter \
250 Applicability::MaybeIncorrect,
258 /// Suggest restricting a type param with a new bound.
259 pub fn suggest_constraining_type_param(
261 generics: &hir::Generics<'_>,
262 err: &mut DiagnosticBuilder<'_>,
265 def_id: Option<DefId>,
267 let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
269 let Some(param) = param else {
273 const MSG_RESTRICT_BOUND_FURTHER: &str = "consider further restricting this bound";
274 let msg_restrict_type = format!("consider restricting type parameter `{}`", param_name);
275 let msg_restrict_type_further =
276 format!("consider further restricting type parameter `{}`", param_name);
278 if def_id == tcx.lang_items().sized_trait() {
279 // Type parameters are already `Sized` by default.
280 err.span_label(param.span, &format!("this type parameter needs to be `{}`", constraint));
281 suggest_removing_unsized_bound(generics, err, param_name, param, def_id);
284 let mut suggest_restrict = |span| {
285 err.span_suggestion_verbose(
287 MSG_RESTRICT_BOUND_FURTHER,
288 format!(" + {}", constraint),
289 Applicability::MachineApplicable,
293 if param_name.starts_with("impl ") {
294 // If there's an `impl Trait` used in argument position, suggest
297 // fn foo(t: impl Foo) { ... }
300 // help: consider further restricting this bound with `+ Bar`
302 // Suggestion for tools in this case is:
304 // fn foo(t: impl Foo) { ... }
307 // replace with: `impl Foo + Bar`
309 suggest_restrict(param.span.shrink_to_hi());
313 if generics.where_clause.predicates.is_empty()
314 // Given `trait Base<T = String>: Super<T>` where `T: Copy`, suggest restricting in the
315 // `where` clause instead of `trait Base<T: Copy = String>: Super<T>`.
316 && !matches!(param.kind, hir::GenericParamKind::Type { default: Some(_), .. })
318 if let Some(span) = param.bounds_span_for_suggestions() {
319 // If user has provided some bounds, suggest restricting them:
321 // fn foo<T: Foo>(t: T) { ... }
324 // help: consider further restricting this bound with `+ Bar`
326 // Suggestion for tools in this case is:
328 // fn foo<T: Foo>(t: T) { ... }
331 // replace with: `T: Bar +`
332 suggest_restrict(span);
334 // If user hasn't provided any bounds, suggest adding a new one:
336 // fn foo<T>(t: T) { ... }
337 // - help: consider restricting this type parameter with `T: Foo`
338 err.span_suggestion_verbose(
339 param.span.shrink_to_hi(),
341 format!(": {}", constraint),
342 Applicability::MachineApplicable,
348 // This part is a bit tricky, because using the `where` clause user can
349 // provide zero, one or many bounds for the same type parameter, so we
350 // have following cases to consider:
352 // 1) When the type parameter has been provided zero bounds
355 // fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
356 // - help: consider restricting this type parameter with `where X: Bar`
359 // fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
360 // - insert: `, X: Bar`
363 // 2) When the type parameter has been provided one bound
366 // fn foo<T>(t: T) where T: Foo { ... }
369 // help: consider further restricting this bound with `+ Bar`
372 // fn foo<T>(t: T) where T: Foo { ... }
375 // replace with: `T: Bar +`
378 // 3) When the type parameter has been provided many bounds
381 // fn foo<T>(t: T) where T: Foo, T: Bar {... }
382 // - help: consider further restricting this type parameter with `where T: Zar`
385 // fn foo<T>(t: T) where T: Foo, T: Bar {... }
386 // - insert: `, T: Zar`
388 // Additionally, there may be no `where` clause whatsoever in the case that this was
389 // reached because the generic parameter has a default:
392 // trait Foo<T=()> {... }
393 // - help: consider further restricting this type parameter with `where T: Zar`
396 // trait Foo<T=()> where T: Zar {... }
397 // - insert: `where T: Zar`
399 if matches!(param.kind, hir::GenericParamKind::Type { default: Some(_), .. })
400 && generics.where_clause.predicates.len() == 0
402 // Suggest a bound, but there is no existing `where` clause *and* the type param has a
403 // default (`<T=Foo>`), so we suggest adding `where T: Bar`.
404 err.span_suggestion_verbose(
405 generics.where_clause.tail_span_for_suggestion(),
406 &msg_restrict_type_further,
407 format!(" where {}: {}", param_name, constraint),
408 Applicability::MachineApplicable,
411 let mut param_spans = Vec::new();
413 for predicate in generics.where_clause.predicates {
414 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
420 if let TyKind::Path(QPath::Resolved(_, path)) = &bounded_ty.kind {
421 if let Some(segment) = path.segments.first() {
422 if segment.ident.to_string() == param_name {
423 param_spans.push(span);
430 match param_spans[..] {
431 [¶m_span] => suggest_restrict(param_span.shrink_to_hi()),
433 err.span_suggestion_verbose(
434 generics.where_clause.tail_span_for_suggestion(),
435 &msg_restrict_type_further,
436 format!(", {}: {}", param_name, constraint),
437 Applicability::MachineApplicable,
447 /// Collect al types that have an implicit `'static` obligation that we could suggest `'_` for.
448 pub struct TraitObjectVisitor<'tcx>(pub Vec<&'tcx hir::Ty<'tcx>>, pub crate::hir::map::Map<'tcx>);
450 impl<'v> hir::intravisit::Visitor<'v> for TraitObjectVisitor<'v> {
451 fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
453 hir::TyKind::TraitObject(
457 hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Static,
464 hir::TyKind::OpaqueDef(item_id, _) => {
466 let item = self.1.item(item_id);
467 hir::intravisit::walk_item(self, item);
471 hir::intravisit::walk_ty(self, ty);
475 /// Collect al types that have an implicit `'static` obligation that we could suggest `'_` for.
476 pub struct StaticLifetimeVisitor<'tcx>(pub Vec<Span>, pub crate::hir::map::Map<'tcx>);
478 impl<'v> hir::intravisit::Visitor<'v> for StaticLifetimeVisitor<'v> {
479 fn visit_lifetime(&mut self, lt: &'v hir::Lifetime) {
480 if let hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Static =
483 self.0.push(lt.span);