]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/diagnostics.rs
Auto merge of #104334 - compiler-errors:ufcs-sugg-wrong-def-id, r=estebank
[rust.git] / compiler / rustc_middle / src / ty / diagnostics.rs
1 //! Diagnostics related methods for `Ty`.
2
3 use std::ops::ControlFlow;
4
5 use crate::ty::{
6     visit::TypeVisitable, AliasTy, Const, ConstKind, DefIdTree, InferConst, InferTy, Opaque,
7     PolyTraitPredicate, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor,
8 };
9
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_errors::{Applicability, Diagnostic, DiagnosticArgValue, IntoDiagnosticArg};
12 use rustc_hir as hir;
13 use rustc_hir::def_id::DefId;
14 use rustc_hir::WherePredicate;
15 use rustc_span::Span;
16 use rustc_type_ir::sty::TyKind::*;
17
18 impl<'tcx> IntoDiagnosticArg for Ty<'tcx> {
19     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
20         format!("{}", self).into_diagnostic_arg()
21     }
22 }
23
24 impl<'tcx> Ty<'tcx> {
25     /// Similar to `Ty::is_primitive`, but also considers inferred numeric values to be primitive.
26     pub fn is_primitive_ty(self) -> bool {
27         matches!(
28             self.kind(),
29             Bool | Char
30                 | Str
31                 | Int(_)
32                 | Uint(_)
33                 | Float(_)
34                 | Infer(
35                     InferTy::IntVar(_)
36                         | InferTy::FloatVar(_)
37                         | InferTy::FreshIntTy(_)
38                         | InferTy::FreshFloatTy(_)
39                 )
40         )
41     }
42
43     /// Whether the type is succinctly representable as a type instead of just referred to with a
44     /// description in error messages. This is used in the main error message.
45     pub fn is_simple_ty(self) -> bool {
46         match self.kind() {
47             Bool
48             | Char
49             | Str
50             | Int(_)
51             | Uint(_)
52             | Float(_)
53             | Infer(
54                 InferTy::IntVar(_)
55                 | InferTy::FloatVar(_)
56                 | InferTy::FreshIntTy(_)
57                 | InferTy::FreshFloatTy(_),
58             ) => true,
59             Ref(_, x, _) | Array(x, _) | Slice(x) => x.peel_refs().is_simple_ty(),
60             Tuple(tys) if tys.is_empty() => true,
61             _ => false,
62         }
63     }
64
65     /// Whether the type is succinctly representable as a type instead of just referred to with a
66     /// description in error messages. This is used in the primary span label. Beyond what
67     /// `is_simple_ty` includes, it also accepts ADTs with no type arguments and references to
68     /// ADTs with no type arguments.
69     pub fn is_simple_text(self) -> bool {
70         match self.kind() {
71             Adt(_, substs) => substs.non_erasable_generics().next().is_none(),
72             Ref(_, ty, _) => ty.is_simple_text(),
73             _ => self.is_simple_ty(),
74         }
75     }
76 }
77
78 pub trait IsSuggestable<'tcx> {
79     /// Whether this makes sense to suggest in a diagnostic.
80     ///
81     /// We filter out certain types and constants since they don't provide
82     /// meaningful rendered suggestions when pretty-printed. We leave some
83     /// nonsense, such as region vars, since those render as `'_` and are
84     /// usually okay to reinterpret as elided lifetimes.
85     ///
86     /// Only if `infer_suggestable` is true, we consider type and const
87     /// inference variables to be suggestable.
88     fn is_suggestable(self, tcx: TyCtxt<'tcx>, infer_suggestable: bool) -> bool;
89 }
90
91 impl<'tcx, T> IsSuggestable<'tcx> for T
92 where
93     T: TypeVisitable<'tcx>,
94 {
95     fn is_suggestable(self, tcx: TyCtxt<'tcx>, infer_suggestable: bool) -> bool {
96         self.visit_with(&mut IsSuggestableVisitor { tcx, infer_suggestable }).is_continue()
97     }
98 }
99
100 pub fn suggest_arbitrary_trait_bound<'tcx>(
101     tcx: TyCtxt<'tcx>,
102     generics: &hir::Generics<'_>,
103     err: &mut Diagnostic,
104     trait_pred: PolyTraitPredicate<'tcx>,
105     associated_ty: Option<(&'static str, Ty<'tcx>)>,
106 ) -> bool {
107     if !trait_pred.is_suggestable(tcx, false) {
108         return false;
109     }
110
111     let param_name = trait_pred.skip_binder().self_ty().to_string();
112     let mut constraint = trait_pred.print_modifiers_and_trait_path().to_string();
113
114     if let Some((name, term)) = associated_ty {
115         // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
116         // That should be extracted into a helper function.
117         if constraint.ends_with('>') {
118             constraint = format!("{}, {} = {}>", &constraint[..constraint.len() - 1], name, term);
119         } else {
120             constraint.push_str(&format!("<{} = {}>", name, term));
121         }
122     }
123
124     let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
125
126     // Skip, there is a param named Self
127     if param.is_some() && param_name == "Self" {
128         return false;
129     }
130
131     // Suggest a where clause bound for a non-type parameter.
132     err.span_suggestion_verbose(
133         generics.tail_span_for_predicate_suggestion(),
134         &format!(
135             "consider {} `where` clause, but there might be an alternative better way to express \
136              this requirement",
137             if generics.where_clause_span.is_empty() { "introducing a" } else { "extending the" },
138         ),
139         format!("{} {}: {}", generics.add_where_or_trailing_comma(), param_name, constraint),
140         Applicability::MaybeIncorrect,
141     );
142     true
143 }
144
145 #[derive(Debug)]
146 enum SuggestChangingConstraintsMessage<'a> {
147     RestrictBoundFurther,
148     RestrictType { ty: &'a str },
149     RestrictTypeFurther { ty: &'a str },
150     RemovingQSized,
151 }
152
153 fn suggest_removing_unsized_bound(
154     generics: &hir::Generics<'_>,
155     suggestions: &mut Vec<(Span, String, SuggestChangingConstraintsMessage<'_>)>,
156     param: &hir::GenericParam<'_>,
157     def_id: Option<DefId>,
158 ) {
159     // See if there's a `?Sized` bound that can be removed to suggest that.
160     // First look at the `where` clause because we can have `where T: ?Sized`,
161     // then look at params.
162     for (where_pos, predicate) in generics.predicates.iter().enumerate() {
163         let WherePredicate::BoundPredicate(predicate) = predicate else {
164             continue;
165         };
166         if !predicate.is_param_bound(param.def_id.to_def_id()) {
167             continue;
168         };
169
170         for (pos, bound) in predicate.bounds.iter().enumerate() {
171             let hir::GenericBound::Trait(poly, hir::TraitBoundModifier::Maybe) = bound else {
172                 continue;
173             };
174             if poly.trait_ref.trait_def_id() != def_id {
175                 continue;
176             }
177             let sp = generics.span_for_bound_removal(where_pos, pos);
178             suggestions.push((
179                 sp,
180                 String::new(),
181                 SuggestChangingConstraintsMessage::RemovingQSized,
182             ));
183         }
184     }
185 }
186
187 /// Suggest restricting a type param with a new bound.
188 pub fn suggest_constraining_type_param(
189     tcx: TyCtxt<'_>,
190     generics: &hir::Generics<'_>,
191     err: &mut Diagnostic,
192     param_name: &str,
193     constraint: &str,
194     def_id: Option<DefId>,
195 ) -> bool {
196     suggest_constraining_type_params(
197         tcx,
198         generics,
199         err,
200         [(param_name, constraint, def_id)].into_iter(),
201     )
202 }
203
204 /// Suggest restricting a type param with a new bound.
205 pub fn suggest_constraining_type_params<'a>(
206     tcx: TyCtxt<'_>,
207     generics: &hir::Generics<'_>,
208     err: &mut Diagnostic,
209     param_names_and_constraints: impl Iterator<Item = (&'a str, &'a str, Option<DefId>)>,
210 ) -> bool {
211     let mut grouped = FxHashMap::default();
212     param_names_and_constraints.for_each(|(param_name, constraint, def_id)| {
213         grouped.entry(param_name).or_insert(Vec::new()).push((constraint, def_id))
214     });
215
216     let mut applicability = Applicability::MachineApplicable;
217     let mut suggestions = Vec::new();
218
219     for (param_name, mut constraints) in grouped {
220         let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);
221         let Some(param) = param else { return false };
222
223         {
224             let mut sized_constraints =
225                 constraints.drain_filter(|(_, def_id)| *def_id == tcx.lang_items().sized_trait());
226             if let Some((constraint, def_id)) = sized_constraints.next() {
227                 applicability = Applicability::MaybeIncorrect;
228
229                 err.span_label(
230                     param.span,
231                     &format!("this type parameter needs to be `{}`", constraint),
232                 );
233                 suggest_removing_unsized_bound(generics, &mut suggestions, param, def_id);
234             }
235         }
236
237         if constraints.is_empty() {
238             continue;
239         }
240
241         let mut constraint = constraints.iter().map(|&(c, _)| c).collect::<Vec<_>>();
242         constraint.sort();
243         constraint.dedup();
244         let constraint = constraint.join(" + ");
245         let mut suggest_restrict = |span, bound_list_non_empty| {
246             suggestions.push((
247                 span,
248                 if bound_list_non_empty {
249                     format!(" + {}", constraint)
250                 } else {
251                     format!(" {}", constraint)
252                 },
253                 SuggestChangingConstraintsMessage::RestrictBoundFurther,
254             ))
255         };
256
257         // When the type parameter has been provided bounds
258         //
259         //    Message:
260         //      fn foo<T>(t: T) where T: Foo { ... }
261         //                            ^^^^^^
262         //                            |
263         //                            help: consider further restricting this bound with `+ Bar`
264         //
265         //    Suggestion:
266         //      fn foo<T>(t: T) where T: Foo { ... }
267         //                                  ^
268         //                                  |
269         //                                  replace with: ` + Bar`
270         //
271         // Or, if user has provided some bounds, suggest restricting them:
272         //
273         //   fn foo<T: Foo>(t: T) { ... }
274         //             ---
275         //             |
276         //             help: consider further restricting this bound with `+ Bar`
277         //
278         // Suggestion for tools in this case is:
279         //
280         //   fn foo<T: Foo>(t: T) { ... }
281         //          --
282         //          |
283         //          replace with: `T: Bar +`
284         if let Some(span) = generics.bounds_span_for_suggestions(param.def_id) {
285             suggest_restrict(span, true);
286             continue;
287         }
288
289         if generics.has_where_clause_predicates {
290             // This part is a bit tricky, because using the `where` clause user can
291             // provide zero, one or many bounds for the same type parameter, so we
292             // have following cases to consider:
293             //
294             // When the type parameter has been provided zero bounds
295             //
296             //    Message:
297             //      fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
298             //             - help: consider restricting this type parameter with `where X: Bar`
299             //
300             //    Suggestion:
301             //      fn foo<X, Y>(x: X, y: Y) where Y: Foo { ... }
302             //                                           - insert: `, X: Bar`
303             suggestions.push((
304                 generics.tail_span_for_predicate_suggestion(),
305                 constraints
306                     .iter()
307                     .map(|&(constraint, _)| format!(", {}: {}", param_name, constraint))
308                     .collect::<String>(),
309                 SuggestChangingConstraintsMessage::RestrictTypeFurther { ty: param_name },
310             ));
311             continue;
312         }
313
314         // Additionally, there may be no `where` clause but the generic parameter has a default:
315         //
316         //    Message:
317         //      trait Foo<T=()> {... }
318         //                - help: consider further restricting this type parameter with `where T: Zar`
319         //
320         //    Suggestion:
321         //      trait Foo<T=()> {... }
322         //                     - insert: `where T: Zar`
323         if matches!(param.kind, hir::GenericParamKind::Type { default: Some(_), .. }) {
324             // Suggest a bound, but there is no existing `where` clause *and* the type param has a
325             // default (`<T=Foo>`), so we suggest adding `where T: Bar`.
326             suggestions.push((
327                 generics.tail_span_for_predicate_suggestion(),
328                 format!(" where {}: {}", param_name, constraint),
329                 SuggestChangingConstraintsMessage::RestrictTypeFurther { ty: param_name },
330             ));
331             continue;
332         }
333
334         // If user has provided a colon, don't suggest adding another:
335         //
336         //   fn foo<T:>(t: T) { ... }
337         //            - insert: consider restricting this type parameter with `T: Foo`
338         if let Some(colon_span) = param.colon_span {
339             suggestions.push((
340                 colon_span.shrink_to_hi(),
341                 format!(" {}", constraint),
342                 SuggestChangingConstraintsMessage::RestrictType { ty: param_name },
343             ));
344             continue;
345         }
346
347         // If user hasn't provided any bounds, suggest adding a new one:
348         //
349         //   fn foo<T>(t: T) { ... }
350         //          - help: consider restricting this type parameter with `T: Foo`
351         suggestions.push((
352             param.span.shrink_to_hi(),
353             format!(": {}", constraint),
354             SuggestChangingConstraintsMessage::RestrictType { ty: param_name },
355         ));
356     }
357
358     // FIXME: remove the suggestions that are from derive, as the span is not correct
359     suggestions = suggestions
360         .into_iter()
361         .filter(|(span, _, _)| !span.in_derive_expansion())
362         .collect::<Vec<_>>();
363
364     if suggestions.len() == 1 {
365         let (span, suggestion, msg) = suggestions.pop().unwrap();
366
367         let s;
368         let msg = match msg {
369             SuggestChangingConstraintsMessage::RestrictBoundFurther => {
370                 "consider further restricting this bound"
371             }
372             SuggestChangingConstraintsMessage::RestrictType { ty } => {
373                 s = format!("consider restricting type parameter `{}`", ty);
374                 &s
375             }
376             SuggestChangingConstraintsMessage::RestrictTypeFurther { ty } => {
377                 s = format!("consider further restricting type parameter `{}`", ty);
378                 &s
379             }
380             SuggestChangingConstraintsMessage::RemovingQSized => {
381                 "consider removing the `?Sized` bound to make the type parameter `Sized`"
382             }
383         };
384
385         err.span_suggestion_verbose(span, msg, suggestion, applicability);
386     } else if suggestions.len() > 1 {
387         err.multipart_suggestion_verbose(
388             "consider restricting type parameters",
389             suggestions.into_iter().map(|(span, suggestion, _)| (span, suggestion)).collect(),
390             applicability,
391         );
392     }
393
394     true
395 }
396
397 /// Collect al types that have an implicit `'static` obligation that we could suggest `'_` for.
398 pub struct TraitObjectVisitor<'tcx>(pub Vec<&'tcx hir::Ty<'tcx>>, pub crate::hir::map::Map<'tcx>);
399
400 impl<'v> hir::intravisit::Visitor<'v> for TraitObjectVisitor<'v> {
401     fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
402         match ty.kind {
403             hir::TyKind::TraitObject(
404                 _,
405                 hir::Lifetime {
406                     res:
407                         hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Static,
408                     ..
409                 },
410                 _,
411             ) => {
412                 self.0.push(ty);
413             }
414             hir::TyKind::OpaqueDef(item_id, _, _) => {
415                 self.0.push(ty);
416                 let item = self.1.item(item_id);
417                 hir::intravisit::walk_item(self, item);
418             }
419             _ => {}
420         }
421         hir::intravisit::walk_ty(self, ty);
422     }
423 }
424
425 /// Collect al types that have an implicit `'static` obligation that we could suggest `'_` for.
426 pub struct StaticLifetimeVisitor<'tcx>(pub Vec<Span>, pub crate::hir::map::Map<'tcx>);
427
428 impl<'v> hir::intravisit::Visitor<'v> for StaticLifetimeVisitor<'v> {
429     fn visit_lifetime(&mut self, lt: &'v hir::Lifetime) {
430         if let hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Static = lt.res
431         {
432             self.0.push(lt.ident.span);
433         }
434     }
435 }
436
437 pub struct IsSuggestableVisitor<'tcx> {
438     tcx: TyCtxt<'tcx>,
439     infer_suggestable: bool,
440 }
441
442 impl<'tcx> TypeVisitor<'tcx> for IsSuggestableVisitor<'tcx> {
443     type BreakTy = ();
444
445     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
446         match t.kind() {
447             Infer(InferTy::TyVar(_)) if self.infer_suggestable => {}
448
449             FnDef(..)
450             | Closure(..)
451             | Infer(..)
452             | Generator(..)
453             | GeneratorWitness(..)
454             | Bound(_, _)
455             | Placeholder(_)
456             | Error(_) => {
457                 return ControlFlow::Break(());
458             }
459
460             Alias(Opaque, AliasTy { def_id, .. }) => {
461                 let parent = self.tcx.parent(*def_id);
462                 if let hir::def::DefKind::TyAlias | hir::def::DefKind::AssocTy = self.tcx.def_kind(parent)
463                     && let Alias(Opaque, AliasTy { def_id: parent_opaque_def_id, .. }) = self.tcx.type_of(parent).kind()
464                     && parent_opaque_def_id == def_id
465                 {
466                     // Okay
467                 } else {
468                     return ControlFlow::Break(());
469                 }
470             }
471
472             Param(param) => {
473                 // FIXME: It would be nice to make this not use string manipulation,
474                 // but it's pretty hard to do this, since `ty::ParamTy` is missing
475                 // sufficient info to determine if it is synthetic, and we don't
476                 // always have a convenient way of getting `ty::Generics` at the call
477                 // sites we invoke `IsSuggestable::is_suggestable`.
478                 if param.name.as_str().starts_with("impl ") {
479                     return ControlFlow::Break(());
480                 }
481             }
482
483             _ => {}
484         }
485
486         t.super_visit_with(self)
487     }
488
489     fn visit_const(&mut self, c: Const<'tcx>) -> ControlFlow<Self::BreakTy> {
490         match c.kind() {
491             ConstKind::Infer(InferConst::Var(_)) if self.infer_suggestable => {}
492
493             ConstKind::Infer(..)
494             | ConstKind::Bound(..)
495             | ConstKind::Placeholder(..)
496             | ConstKind::Error(..) => {
497                 return ControlFlow::Break(());
498             }
499             _ => {}
500         }
501
502         c.super_visit_with(self)
503     }
504 }