Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead · rust-lang/rust@847c422 · GitHub
Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead · rust-lang/rust@847c422 · GitHub
Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead · rust-lang/rust@847c422 · GitHub
Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead · rust-lang/rust@847c422 · GitHub
Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead · rust-lang/rust@847c422 · GitHub
Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead · rust-lang/rust@847c422 · GitHub
Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead · rust-lang/rust@847c422 · GitHub
Skip to content

Commit 847c422

Browse files
authored
Rollup merge of #147171 - Qelxiros:hashmap_diag, r=fee1-dead
recommend using a HashMap if a HashSet's second generic parameter doesn't implement BuildHasher closes#147147 ~The suggestion span is wrong, but I'm not sure how to find the right one.~ fixed I'm relatively new to the diagnostics ecosystem, so I'm not sure if `span_help` is the right choice. `span_suggestion_*` might be better, but the output from `x test` looks weird in that case.
2 parents 6159a44 + 754a82d commit 847c422

5 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎compiler/rustc_hir_typeck/src/method/suggest.rs‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17541754
err.note(note);
17551755
}
17561756

1757+
iflet ty::Adt(adt_def, _) = rcvr_ty.kind(){
1758+
unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
1759+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1760+
pred.kind().skip_binder()
1761+
{
1762+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
1763+
err,&pred,*adt_def,
1764+
)
1765+
}else{
1766+
false
1767+
}
1768+
});
1769+
}
1770+
17571771
*suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
17581772
*unsatisfied_bounds = true;
17591773
}
@@ -2990,7 +3004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29903004
.filter_map(|e| match e.obligation.predicate.kind().skip_binder(){
29913005
ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
29923006
match pred.self_ty().kind(){
2993-
ty::Adt(_, _) => Some(pred),
3007+
ty::Adt(_, _) => Some((e.root_obligation.predicate,pred)),
29943008
_ => None,
29953009
}
29963010
}
@@ -3000,18 +3014,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30003014

30013015
// Note for local items and foreign items respectively.
30023016
let(mut local_preds,mut foreign_preds):(Vec<_>,Vec<_>) =
3003-
preds.iter().partition(|&pred| {
3017+
preds.iter().partition(|&(_,pred)| {
30043018
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30053019
def.did().is_local()
30063020
}else{
30073021
false
30083022
}
30093023
});
30103024

3011-
local_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3025+
local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
30123026
let local_def_ids = local_preds
30133027
.iter()
3014-
.filter_map(|pred| match pred.self_ty().kind(){
3028+
.filter_map(|(_,pred)| match pred.self_ty().kind(){
30153029
ty::Adt(def, _) => Some(def.did()),
30163030
_ => None,
30173031
})
@@ -3024,7 +3038,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30243038
})
30253039
.collect::<Vec<_>>()
30263040
.into();
3027-
for pred in&local_preds {
3041+
for(_,pred)in&local_preds {
30283042
iflet ty::Adt(def, _) = pred.self_ty().kind(){
30293043
local_spans.push_span_label(
30303044
self.tcx.def_span(def.did()),
@@ -3033,7 +3047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30333047
}
30343048
}
30353049
if local_spans.primary_span().is_some(){
3036-
let msg = iflet[local_pred] = local_preds.as_slice(){
3050+
let msg = iflet[(_,local_pred)] = local_preds.as_slice(){
30373051
format!(
30383052
"an implementation of `{}` might be missing for `{}`",
30393053
local_pred.trait_ref.print_trait_sugared(),
@@ -3051,9 +3065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30513065
err.span_note(local_spans, msg);
30523066
}
30533067

3054-
foreign_preds.sort_by_key(|pred:&&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3068+
foreign_preds
3069+
.sort_by_key(|(_, pred):&(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
30553070

3056-
for pred in foreign_preds {
3071+
for(_,pred)in&foreign_preds {
30573072
let ty = pred.self_ty();
30583073
let ty::Adt(def, _) = ty.kind()else{continue};
30593074
let span = self.tcx.def_span(def.did());
@@ -3066,6 +3081,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30663081
mspan,
30673082
format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
30683083
);
3084+
3085+
foreign_preds.iter().find(|&(root_pred, pred)| {
3086+
iflet ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3087+
root_pred.kind().skip_binder()
3088+
&& letSome(root_adt) = root_pred.self_ty().ty_adt_def()
3089+
{
3090+
self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3091+
}else{
3092+
false
3093+
}
3094+
});
30693095
}
30703096

30713097
let preds:Vec<_> = errors
@@ -4388,6 +4414,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43884414

43894415
self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
43904416
}
4417+
4418+
fnsuggest_hashmap_on_unsatisfied_hashset_buildhasher(
4419+
&self,
4420+
err:&mutDiag<'_>,
4421+
pred:&ty::TraitPredicate<'_>,
4422+
adt: ty::AdtDef<'_>,
4423+
) -> bool{
4424+
ifself.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4425+
&& self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4426+
{
4427+
err.help("you might have intended to use a HashMap instead");
4428+
true
4429+
}else{
4430+
false
4431+
}
4432+
}
43914433
}
43924434

43934435
#[derive(Copy,Clone,Debug)]

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ symbols! {
191191
Borrow,
192192
BorrowMut,
193193
Break,
194+
BuildHasher,
194195
C,
195196
CStr,
196197
C_dash_unwind:"C-unwind",

‎library/core/src/hash/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ impl<H: Hasher + ?Sized> Hasher for &mut H {
633633
///
634634
/// [`build_hasher`]: BuildHasher::build_hasher
635635
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
636+
#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
636637
#[stable(since = "1.7.0", feature = "build_hasher")]
637638
pubtraitBuildHasher{
638639
/// Type of the hasher that will be created.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::collections::HashSet;
2+
3+
#[derive(PartialEq)]
4+
//~^ NOTE in this expansion of
5+
//~| NOTE in this expansion of
6+
//~| NOTE in this expansion of
7+
pubstructMyStruct{
8+
pubparameters:HashSet<String,String>,
9+
//~^ NOTE `String` does not implement `BuildHasher`
10+
//~| ERROR binary operation
11+
//~| HELP use a HashMap
12+
}
13+
14+
fnmain(){
15+
let h1 = HashSet::<usize,usize>::with_hasher(0);
16+
h1.insert(1);
17+
//~^ ERROR its trait bounds were not satisfied
18+
//~| NOTE the following trait bounds
19+
//~| HELP use a HashMap
20+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0369]: binary operation `==` cannot be applied to type `HashSet<String, String>`
2+
--> $DIR/hashset_generics.rs:8:5
3+
|
4+
LL | #[derive(PartialEq)]
5+
| --------- in this derive macro expansion
6+
...
7+
LL | pub parameters: HashSet<String, String>,
8+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9+
|
10+
note: `String` does not implement `BuildHasher`
11+
--> $SRC_DIR/alloc/src/string.rs:LL:COL
12+
|
13+
= note: `String` is defined in another crate
14+
= help: you might have intended to use a HashMap instead
15+
16+
error[E0599]: the method `insert` exists for struct `HashSet<usize, usize>`, but its trait bounds were not satisfied
17+
--> $DIR/hashset_generics.rs:16:8
18+
|
19+
LL | h1.insert(1);
20+
| ^^^^^^
21+
|
22+
= note: the following trait bounds were not satisfied:
23+
`usize: BuildHasher`
24+
= help: you might have intended to use a HashMap instead
25+
26+
error: aborting due to 2 previous errors
27+
28+
Some errors have detailed explanations: E0369, E0599.
29+
For more information about an error, try `rustc --explain E0369`.

0 commit comments

Comments
 (0)