Skip to content

Commit e38f163

Browse files
committed
Suggest <_ as Default>::default() when given <Default>::default()
1 parent 39ce238 commit e38f163

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use rustc_ast::TraitObjectSyntax;
22
use rustc_errors::{codes::*, Diag, EmissionGuarantee, ErrorGuaranteed, StashKey};
33
use rustc_hir as hir;
44
use rustc_hir::def::{DefKind, Res};
5+
use rustc_infer::traits::error_reporting::suggest_path_on_bare_trait;
56
use rustc_lint_defs::{builtin::BARE_TRAIT_OBJECTS, Applicability};
67
use rustc_span::Span;
78
use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
@@ -80,6 +81,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
8081
);
8182
}
8283
}
84+
85+
if !object_safe && self_ty.span.can_be_used_for_suggestions() {
86+
// suggest_impl_trait_on_bare_trait(tcx, &mut diag, self_ty);
87+
let parent = tcx.parent_hir_node(self_ty.hir_id);
88+
suggest_path_on_bare_trait(tcx, &mut diag, parent);
89+
}
90+
8391
// Check if the impl trait that we are considering is an impl of a local trait.
8492
self.maybe_suggest_blanket_trait_impl(self_ty, &mut diag);
8593
self.maybe_suggest_assoc_ty_bound(self_ty, &mut diag);

tests/ui/dyn-keyword/trait-missing-dyn-in-qualified-path.edition2021.stderr

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,21 @@ error[E0782]: trait objects must include the `dyn` keyword
33
|
44
LL | let x: u32 = <Default>::default();
55
| ^^^^^^^
6+
|
7+
= help: when writing `<Default>::default` you are requiring `Default` be "object safe", which it isn't
8+
help: you might have meant to access the associated function of a specific `impl` to avoid requiring "object safety" from `Default`, either with some explicit type...
9+
|
10+
LL | let x: u32 = </* Type */ as Default>::default();
11+
| +++++++++++++
12+
help: ...or rely on inference if the compiler has enough context to identify the desired type on its own...
13+
|
14+
LL - let x: u32 = <Default>::default();
15+
LL + let x: u32 = Default::default();
16+
|
17+
help: ...which is equivalent to
18+
|
19+
LL | let x: u32 = <_ as Default>::default();
20+
| ++++
621

722
error: aborting due to 1 previous error
823

0 commit comments

Comments
 (0)