rustc_hir_analysis/hir_ty_lowering/
lint.rs
1use rustc_ast::TraitObjectSyntax;
2use rustc_errors::codes::*;
3use rustc_errors::{Diag, EmissionGuarantee, ErrorGuaranteed, StashKey, Suggestions};
4use rustc_hir as hir;
5use rustc_hir::def::{DefKind, Namespace, Res};
6use rustc_hir::def_id::DefId;
7use rustc_lint_defs::Applicability;
8use rustc_lint_defs::builtin::BARE_TRAIT_OBJECTS;
9use rustc_span::Span;
10use rustc_span::edit_distance::find_best_match_for_name;
11use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName;
12
13use super::HirTyLowerer;
14
15impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
16 pub(super) fn prohibit_or_lint_bare_trait_object_ty(
21 &self,
22 self_ty: &hir::Ty<'_>,
23 ) -> Option<ErrorGuaranteed> {
24 let tcx = self.tcx();
25
26 let poly_trait_ref = if let hir::TyKind::TraitObject([poly_trait_ref, ..], tagged_ptr) =
27 self_ty.kind
28 && let TraitObjectSyntax::None = tagged_ptr.tag()
29 {
30 poly_trait_ref
31 } else {
32 return None;
33 };
34
35 let in_path = match tcx.parent_hir_node(self_ty.hir_id) {
36 hir::Node::Ty(hir::Ty {
37 kind: hir::TyKind::Path(hir::QPath::TypeRelative(qself, _)),
38 ..
39 })
40 | hir::Node::Expr(hir::Expr {
41 kind: hir::ExprKind::Path(hir::QPath::TypeRelative(qself, _)),
42 ..
43 })
44 | hir::Node::PatExpr(hir::PatExpr {
45 kind: hir::PatExprKind::Path(hir::QPath::TypeRelative(qself, _)),
46 ..
47 }) if qself.hir_id == self_ty.hir_id => true,
48 _ => false,
49 };
50 let needs_bracket = in_path
51 && !tcx
52 .sess
53 .source_map()
54 .span_to_prev_source(self_ty.span)
55 .ok()
56 .is_some_and(|s| s.trim_end().ends_with('<'));
57
58 let is_global = poly_trait_ref.trait_ref.path.is_global();
59
60 let mut sugg = vec![(
61 self_ty.span.shrink_to_lo(),
62 format!(
63 "{}dyn {}",
64 if needs_bracket { "<" } else { "" },
65 if is_global { "(" } else { "" },
66 ),
67 )];
68
69 if is_global || needs_bracket {
70 sugg.push((
71 self_ty.span.shrink_to_hi(),
72 format!(
73 "{}{}",
74 if is_global { ")" } else { "" },
75 if needs_bracket { ">" } else { "" },
76 ),
77 ));
78 }
79
80 if self_ty.span.edition().at_least_rust_2021() {
81 let msg = "expected a type, found a trait";
82 let label = "you can add the `dyn` keyword if you want a trait object";
83 let mut diag =
84 rustc_errors::struct_span_code_err!(self.dcx(), self_ty.span, E0782, "{}", msg);
85 if self_ty.span.can_be_used_for_suggestions()
86 && !self.maybe_suggest_impl_trait(self_ty, &mut diag)
87 {
88 diag.multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable);
90 }
91 self.maybe_suggest_blanket_trait_impl(self_ty, &mut diag);
93 self.maybe_suggest_assoc_ty_bound(self_ty, &mut diag);
94 self.maybe_suggest_typoed_method(
95 self_ty,
96 poly_trait_ref.trait_ref.trait_def_id(),
97 &mut diag,
98 );
99 if let Some(mut sugg) =
102 tcx.dcx().steal_non_err(self_ty.span, StashKey::AssociatedTypeSuggestion)
103 && let Suggestions::Enabled(ref mut s1) = diag.suggestions
104 && let Suggestions::Enabled(ref mut s2) = sugg.suggestions
105 {
106 s1.append(s2);
107 sugg.cancel();
108 }
109 Some(diag.emit())
110 } else {
111 tcx.node_span_lint(BARE_TRAIT_OBJECTS, self_ty.hir_id, self_ty.span, |lint| {
112 lint.primary_message("trait objects without an explicit `dyn` are deprecated");
113 if self_ty.span.can_be_used_for_suggestions() {
114 lint.multipart_suggestion_verbose(
115 "if this is a dyn-compatible trait, use `dyn`",
116 sugg,
117 Applicability::MachineApplicable,
118 );
119 }
120 self.maybe_suggest_blanket_trait_impl(self_ty, lint);
121 });
122 None
123 }
124 }
125
126 fn maybe_suggest_blanket_trait_impl<G: EmissionGuarantee>(
128 &self,
129 self_ty: &hir::Ty<'_>,
130 diag: &mut Diag<'_, G>,
131 ) {
132 let tcx = self.tcx();
133 let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
134 if let hir::Node::Item(hir::Item {
135 kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, of_trait, generics, .. }),
136 ..
137 }) = tcx.hir_node_by_def_id(parent_id)
138 && self_ty.hir_id == impl_self_ty.hir_id
139 {
140 let Some(of_trait_ref) = of_trait else {
141 diag.span_suggestion_verbose(
142 impl_self_ty.span.shrink_to_hi(),
143 "you might have intended to implement this trait for a given type",
144 format!(" for /* Type */"),
145 Applicability::HasPlaceholders,
146 );
147 return;
148 };
149 if !of_trait_ref.trait_def_id().is_some_and(|def_id| def_id.is_local()) {
150 return;
151 }
152 let of_trait_span = of_trait_ref.path.span;
153 let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else {
155 return;
156 };
157
158 let Ok(impl_trait_name) = self.tcx().sess.source_map().span_to_snippet(self_ty.span)
159 else {
160 return;
161 };
162 let sugg = self.add_generic_param_suggestion(generics, self_ty.span, &impl_trait_name);
163 diag.multipart_suggestion(
164 format!(
165 "alternatively use a blanket implementation to implement `{of_trait_name}` for \
166 all types that also implement `{impl_trait_name}`"
167 ),
168 sugg,
169 Applicability::MaybeIncorrect,
170 );
171 }
172 }
173
174 fn add_generic_param_suggestion(
175 &self,
176 generics: &hir::Generics<'_>,
177 self_ty_span: Span,
178 impl_trait_name: &str,
179 ) -> Vec<(Span, String)> {
180 let param_name = generics.params.next_type_param_name(None);
182
183 let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
184 (span, format!(", {param_name}: {impl_trait_name}"))
185 } else {
186 (generics.span, format!("<{param_name}: {impl_trait_name}>"))
187 };
188 vec![(self_ty_span, param_name), add_generic_sugg]
189 }
190
191 fn maybe_suggest_impl_trait(&self, self_ty: &hir::Ty<'_>, diag: &mut Diag<'_>) -> bool {
193 let tcx = self.tcx();
194 let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
195 let (sig, generics) = match tcx.hir_node_by_def_id(parent_id) {
202 hir::Node::Item(hir::Item {
203 kind: hir::ItemKind::Fn { sig, generics, .. }, ..
204 }) => (sig, generics),
205 hir::Node::TraitItem(hir::TraitItem {
206 kind: hir::TraitItemKind::Fn(sig, _),
207 generics,
208 ..
209 }) => (sig, generics),
210 hir::Node::ImplItem(hir::ImplItem {
211 kind: hir::ImplItemKind::Fn(sig, _),
212 generics,
213 ..
214 }) => (sig, generics),
215 _ => return false,
216 };
217 let Ok(trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else {
218 return false;
219 };
220 let impl_sugg = vec![(self_ty.span.shrink_to_lo(), "impl ".to_string())];
221 let is_dyn_compatible = match self_ty.kind {
223 hir::TyKind::TraitObject(objects, ..) => {
224 objects.iter().all(|o| match o.trait_ref.path.res {
225 Res::Def(DefKind::Trait, id) => tcx.is_dyn_compatible(id),
226 _ => false,
227 })
228 }
229 _ => false,
230 };
231
232 let borrowed = matches!(
233 tcx.parent_hir_node(self_ty.hir_id),
234 hir::Node::Ty(hir::Ty { kind: hir::TyKind::Ref(..), .. })
235 );
236
237 if let hir::FnRetTy::Return(ty) = sig.decl.output
239 && ty.peel_refs().hir_id == self_ty.hir_id
240 {
241 let pre = if !is_dyn_compatible {
242 format!("`{trait_name}` is dyn-incompatible, ")
243 } else {
244 String::new()
245 };
246 let msg = format!(
247 "{pre}use `impl {trait_name}` to return an opaque type, as long as you return a \
248 single underlying type",
249 );
250
251 diag.multipart_suggestion_verbose(msg, impl_sugg, Applicability::MachineApplicable);
252
253 if is_dyn_compatible {
255 let suggestion = if borrowed {
259 vec![(ty.span, format!("Box<dyn {trait_name}>"))]
260 } else {
261 vec![
262 (ty.span.shrink_to_lo(), "Box<dyn ".to_string()),
263 (ty.span.shrink_to_hi(), ">".to_string()),
264 ]
265 };
266
267 diag.multipart_suggestion_verbose(
268 "alternatively, you can return an owned trait object",
269 suggestion,
270 Applicability::MachineApplicable,
271 );
272 }
273 return true;
274 }
275
276 for ty in sig.decl.inputs {
278 if ty.peel_refs().hir_id != self_ty.hir_id {
279 continue;
280 }
281 let sugg = self.add_generic_param_suggestion(generics, self_ty.span, &trait_name);
282 diag.multipart_suggestion_verbose(
283 format!("use a new generic type parameter, constrained by `{trait_name}`"),
284 sugg,
285 Applicability::MachineApplicable,
286 );
287 diag.multipart_suggestion_verbose(
288 "you can also use an opaque type, but users won't be able to specify the type \
289 parameter when calling the `fn`, having to rely exclusively on type inference",
290 impl_sugg,
291 Applicability::MachineApplicable,
292 );
293 if !is_dyn_compatible {
294 diag.note(format!("`{trait_name}` it is dyn-incompatible, so it can't be `dyn`"));
295 } else {
296 let (dyn_str, paren_dyn_str) =
298 if borrowed { ("dyn ", "(dyn ") } else { ("&dyn ", "&(dyn ") };
299
300 let sugg = if let hir::TyKind::TraitObject([_, _, ..], _) = self_ty.kind {
301 vec![
303 (self_ty.span.shrink_to_lo(), paren_dyn_str.to_string()),
304 (self_ty.span.shrink_to_hi(), ")".to_string()),
305 ]
306 } else {
307 vec![(self_ty.span.shrink_to_lo(), dyn_str.to_string())]
308 };
309 diag.multipart_suggestion_verbose(
310 format!(
311 "alternatively, use a trait object to accept any type that implements \
312 `{trait_name}`, accessing its methods at runtime using dynamic dispatch",
313 ),
314 sugg,
315 Applicability::MachineApplicable,
316 );
317 }
318 return true;
319 }
320 false
321 }
322
323 fn maybe_suggest_assoc_ty_bound(&self, self_ty: &hir::Ty<'_>, diag: &mut Diag<'_>) {
324 let mut parents = self.tcx().hir().parent_iter(self_ty.hir_id);
325
326 if let Some((_, hir::Node::AssocItemConstraint(constraint))) = parents.next()
327 && let Some(obj_ty) = constraint.ty()
328 {
329 if let Some((_, hir::Node::TraitRef(..))) = parents.next()
330 && let Some((_, hir::Node::Ty(ty))) = parents.next()
331 && let hir::TyKind::TraitObject(..) = ty.kind
332 {
333 return;
335 }
336
337 let lo = if constraint.gen_args.span_ext.is_dummy() {
338 constraint.ident.span
339 } else {
340 constraint.gen_args.span_ext
341 };
342 let hi = obj_ty.span;
343
344 if !lo.eq_ctxt(hi) {
345 return;
346 }
347
348 diag.span_suggestion_verbose(
349 lo.between(hi),
350 "you might have meant to write a bound here",
351 ": ",
352 Applicability::MaybeIncorrect,
353 );
354 }
355 }
356
357 fn maybe_suggest_typoed_method(
358 &self,
359 self_ty: &hir::Ty<'_>,
360 trait_def_id: Option<DefId>,
361 diag: &mut Diag<'_>,
362 ) {
363 let tcx = self.tcx();
364 let Some(trait_def_id) = trait_def_id else {
365 return;
366 };
367 let hir::Node::Expr(hir::Expr {
368 kind: hir::ExprKind::Path(hir::QPath::TypeRelative(path_ty, segment)),
369 ..
370 }) = tcx.parent_hir_node(self_ty.hir_id)
371 else {
372 return;
373 };
374 if path_ty.hir_id != self_ty.hir_id {
375 return;
376 }
377 let names: Vec<_> = tcx
378 .associated_items(trait_def_id)
379 .in_definition_order()
380 .filter(|assoc| assoc.kind.namespace() == Namespace::ValueNS)
381 .map(|cand| cand.name)
382 .collect();
383 if let Some(typo) = find_best_match_for_name(&names, segment.ident.name, None) {
384 diag.span_suggestion_verbose(
385 segment.ident.span,
386 format!(
387 "you may have misspelled this associated item, causing `{}` \
388 to be interpreted as a type rather than a trait",
389 tcx.item_name(trait_def_id),
390 ),
391 typo,
392 Applicability::MaybeIncorrect,
393 );
394 }
395 }
396}