Skip to content

Commit 568736b

Browse files
authored
Rollup merge of #94689 - compiler-errors:on-unimplemented-substs, r=petrochenkov
Use impl substs in `#[rustc_on_unimplemented]` We were using the trait-ref substs instead of impl substs in `rustc_on_unimplemented`, even when computing the `rustc_on_unimplemented` attached to an impl block. Let's not do that. This PR also untangles impl and trait def-ids in the logic in `on_unimplemented` a bit. Fixes #94675
2 parents 64187b8 + b726bfb commit 568736b

File tree

10 files changed

+129
-42
lines changed

10 files changed

+129
-42
lines changed

compiler/rustc_middle/src/ty/sty.rs

-1
Original file line numberDiff line numberDiff line change
@@ -977,7 +977,6 @@ impl<'tcx> TraitRef<'tcx> {
977977
substs: SubstsRef<'tcx>,
978978
) -> ty::TraitRef<'tcx> {
979979
let defs = tcx.generics_of(trait_id);
980-
981980
ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) }
982981
}
983982
}

compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs

+14-14
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use super::{
44
use crate::infer::InferCtxt;
55
use rustc_hir as hir;
66
use rustc_hir::def_id::DefId;
7-
use rustc_middle::ty::subst::Subst;
7+
use rustc_middle::ty::subst::{Subst, SubstsRef};
88
use rustc_middle::ty::{self, GenericParamDefKind};
99
use rustc_span::symbol::sym;
1010
use std::iter;
@@ -17,7 +17,7 @@ crate trait InferCtxtExt<'tcx> {
1717
&self,
1818
trait_ref: ty::PolyTraitRef<'tcx>,
1919
obligation: &PredicateObligation<'tcx>,
20-
) -> Option<DefId>;
20+
) -> Option<(DefId, SubstsRef<'tcx>)>;
2121

2222
/*private*/
2323
fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str>;
@@ -34,7 +34,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
3434
&self,
3535
trait_ref: ty::PolyTraitRef<'tcx>,
3636
obligation: &PredicateObligation<'tcx>,
37-
) -> Option<DefId> {
37+
) -> Option<(DefId, SubstsRef<'tcx>)> {
3838
let tcx = self.tcx;
3939
let param_env = obligation.param_env;
4040
let trait_ref = tcx.erase_late_bound_regions(trait_ref);
@@ -50,28 +50,29 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
5050
let impl_self_ty = impl_trait_ref.self_ty();
5151

5252
if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
53-
self_match_impls.push(def_id);
53+
self_match_impls.push((def_id, impl_substs));
5454

5555
if iter::zip(
5656
trait_ref.substs.types().skip(1),
5757
impl_trait_ref.substs.types().skip(1),
5858
)
5959
.all(|(u, v)| self.fuzzy_match_tys(u, v, false).is_some())
6060
{
61-
fuzzy_match_impls.push(def_id);
61+
fuzzy_match_impls.push((def_id, impl_substs));
6262
}
6363
}
6464
});
6565

66-
let impl_def_id = if self_match_impls.len() == 1 {
66+
let impl_def_id_and_substs = if self_match_impls.len() == 1 {
6767
self_match_impls[0]
6868
} else if fuzzy_match_impls.len() == 1 {
6969
fuzzy_match_impls[0]
7070
} else {
7171
return None;
7272
};
7373

74-
tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented).then_some(impl_def_id)
74+
tcx.has_attr(impl_def_id_and_substs.0, sym::rustc_on_unimplemented)
75+
.then_some(impl_def_id_and_substs)
7576
}
7677

7778
/// Used to set on_unimplemented's `ItemContext`
@@ -120,8 +121,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
120121
trait_ref: ty::PolyTraitRef<'tcx>,
121122
obligation: &PredicateObligation<'tcx>,
122123
) -> OnUnimplementedNote {
123-
let def_id =
124-
self.impl_similar_to(trait_ref, obligation).unwrap_or_else(|| trait_ref.def_id());
124+
let (def_id, substs) = self
125+
.impl_similar_to(trait_ref, obligation)
126+
.unwrap_or_else(|| (trait_ref.def_id(), trait_ref.skip_binder().substs));
125127
let trait_ref = trait_ref.skip_binder();
126128

127129
let mut flags = vec![(
@@ -176,15 +178,15 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
176178
for param in generics.params.iter() {
177179
let value = match param.kind {
178180
GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
179-
trait_ref.substs[param.index as usize].to_string()
181+
substs[param.index as usize].to_string()
180182
}
181183
GenericParamDefKind::Lifetime => continue,
182184
};
183185
let name = param.name;
184186
flags.push((name, Some(value)));
185187

186188
if let GenericParamDefKind::Type { .. } = param.kind {
187-
let param_ty = trait_ref.substs[param.index as usize].expect_ty();
189+
let param_ty = substs[param.index as usize].expect_ty();
188190
if let Some(def) = param_ty.ty_adt_def() {
189191
// We also want to be able to select the parameter's
190192
// original signature with no type arguments resolved
@@ -229,9 +231,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
229231
}
230232
});
231233

232-
if let Ok(Some(command)) =
233-
OnUnimplementedDirective::of_item(self.tcx, trait_ref.def_id, def_id)
234-
{
234+
if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, def_id) {
235235
command.evaluate(self.tcx, trait_ref, &flags)
236236
} else {
237237
OnUnimplementedNote::default()

compiler/rustc_trait_selection/src/traits/on_unimplemented.rs

+26-20
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ fn parse_error(
5454
impl<'tcx> OnUnimplementedDirective {
5555
fn parse(
5656
tcx: TyCtxt<'tcx>,
57-
trait_def_id: DefId,
57+
item_def_id: DefId,
5858
items: &[NestedMetaItem],
5959
span: Span,
6060
is_root: bool,
@@ -63,7 +63,7 @@ impl<'tcx> OnUnimplementedDirective {
6363
let mut item_iter = items.iter();
6464

6565
let parse_value = |value_str| {
66-
OnUnimplementedFormatString::try_parse(tcx, trait_def_id, value_str, span).map(Some)
66+
OnUnimplementedFormatString::try_parse(tcx, item_def_id, value_str, span).map(Some)
6767
};
6868

6969
let condition = if is_root {
@@ -135,7 +135,7 @@ impl<'tcx> OnUnimplementedDirective {
135135
{
136136
if let Some(items) = item.meta_item_list() {
137137
if let Ok(subcommand) =
138-
Self::parse(tcx, trait_def_id, &items, item.span(), false)
138+
Self::parse(tcx, item_def_id, &items, item.span(), false)
139139
{
140140
subcommands.push(subcommand);
141141
} else {
@@ -178,27 +178,23 @@ impl<'tcx> OnUnimplementedDirective {
178178
}
179179
}
180180

181-
pub fn of_item(
182-
tcx: TyCtxt<'tcx>,
183-
trait_def_id: DefId,
184-
impl_def_id: DefId,
185-
) -> Result<Option<Self>, ErrorGuaranteed> {
186-
let attrs = tcx.get_attrs(impl_def_id);
181+
pub fn of_item(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result<Option<Self>, ErrorGuaranteed> {
182+
let attrs = tcx.get_attrs(item_def_id);
187183

188184
let Some(attr) = tcx.sess.find_by_name(&attrs, sym::rustc_on_unimplemented) else {
189185
return Ok(None);
190186
};
191187

192188
let result = if let Some(items) = attr.meta_item_list() {
193-
Self::parse(tcx, trait_def_id, &items, attr.span, true).map(Some)
189+
Self::parse(tcx, item_def_id, &items, attr.span, true).map(Some)
194190
} else if let Some(value) = attr.value_str() {
195191
Ok(Some(OnUnimplementedDirective {
196192
condition: None,
197193
message: None,
198194
subcommands: vec![],
199195
label: Some(OnUnimplementedFormatString::try_parse(
200196
tcx,
201-
trait_def_id,
197+
item_def_id,
202198
value,
203199
attr.span,
204200
)?),
@@ -209,7 +205,7 @@ impl<'tcx> OnUnimplementedDirective {
209205
} else {
210206
return Err(ErrorGuaranteed);
211207
};
212-
debug!("of_item({:?}/{:?}) = {:?}", trait_def_id, impl_def_id, result);
208+
debug!("of_item({:?}) = {:?}", item_def_id, result);
213209
result
214210
}
215211

@@ -280,23 +276,29 @@ impl<'tcx> OnUnimplementedDirective {
280276
impl<'tcx> OnUnimplementedFormatString {
281277
fn try_parse(
282278
tcx: TyCtxt<'tcx>,
283-
trait_def_id: DefId,
279+
item_def_id: DefId,
284280
from: Symbol,
285281
err_sp: Span,
286282
) -> Result<Self, ErrorGuaranteed> {
287283
let result = OnUnimplementedFormatString(from);
288-
result.verify(tcx, trait_def_id, err_sp)?;
284+
result.verify(tcx, item_def_id, err_sp)?;
289285
Ok(result)
290286
}
291287

292288
fn verify(
293289
&self,
294290
tcx: TyCtxt<'tcx>,
295-
trait_def_id: DefId,
291+
item_def_id: DefId,
296292
span: Span,
297293
) -> Result<(), ErrorGuaranteed> {
298-
let name = tcx.item_name(trait_def_id);
299-
let generics = tcx.generics_of(trait_def_id);
294+
let trait_def_id = if tcx.is_trait(item_def_id) {
295+
item_def_id
296+
} else {
297+
tcx.trait_id_of_impl(item_def_id)
298+
.expect("expected `on_unimplemented` to correspond to a trait")
299+
};
300+
let trait_name = tcx.item_name(trait_def_id);
301+
let generics = tcx.generics_of(item_def_id);
300302
let s = self.0.as_str();
301303
let parser = Parser::new(s, None, None, false, ParseMode::Format);
302304
let mut result = Ok(());
@@ -307,7 +309,7 @@ impl<'tcx> OnUnimplementedFormatString {
307309
// `{Self}` is allowed
308310
Position::ArgumentNamed(s, _) if s == kw::SelfUpper => (),
309311
// `{ThisTraitsName}` is allowed
310-
Position::ArgumentNamed(s, _) if s == name => (),
312+
Position::ArgumentNamed(s, _) if s == trait_name => (),
311313
// `{from_method}` is allowed
312314
Position::ArgumentNamed(s, _) if s == sym::from_method => (),
313315
// `{from_desugaring}` is allowed
@@ -329,9 +331,13 @@ impl<'tcx> OnUnimplementedFormatString {
329331
tcx.sess,
330332
span,
331333
E0230,
332-
"there is no parameter `{}` on trait `{}`",
334+
"there is no parameter `{}` on {}",
333335
s,
334-
name
336+
if trait_def_id == item_def_id {
337+
format!("trait `{}`", trait_name)
338+
} else {
339+
"impl".to_string()
340+
}
335341
)
336342
.emit();
337343
result = Err(ErrorGuaranteed);

compiler/rustc_typeck/src/check/check.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -742,12 +742,11 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
742742
impl_trait_ref,
743743
&impl_.items,
744744
);
745-
let trait_def_id = impl_trait_ref.def_id;
746-
check_on_unimplemented(tcx, trait_def_id, it);
745+
check_on_unimplemented(tcx, it);
747746
}
748747
}
749748
hir::ItemKind::Trait(_, _, _, _, ref items) => {
750-
check_on_unimplemented(tcx, it.def_id.to_def_id(), it);
749+
check_on_unimplemented(tcx, it);
751750

752751
for item in items.iter() {
753752
let item = tcx.hir().trait_item(item.id);
@@ -857,9 +856,9 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
857856
}
858857
}
859858

860-
pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
859+
pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
861860
// an error would be reported if this fails.
862-
let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id());
861+
let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
863862
}
864863

865864
pub(super) fn check_specialization_validity<'tcx>(

src/test/ui/consts/issue-94675.rs

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#![feature(const_trait_impl, const_mut_refs)]
2+
3+
struct Foo<'a> {
4+
bar: &'a mut Vec<usize>,
5+
}
6+
7+
impl<'a> Foo<'a> {
8+
const fn spam(&mut self, baz: &mut Vec<u32>) {
9+
self.bar[0] = baz.len();
10+
//~^ ERROR cannot call non-const fn `Vec::<u32>::len` in constant functions
11+
//~| ERROR the trait bound `Vec<usize>: ~const IndexMut<usize>` is not satisfied
12+
//~| ERROR cannot call non-const operator in constant functions
13+
}
14+
}
15+
16+
fn main() {}

src/test/ui/consts/issue-94675.stderr

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
error[E0015]: cannot call non-const fn `Vec::<u32>::len` in constant functions
2+
--> $DIR/issue-94675.rs:9:27
3+
|
4+
LL | self.bar[0] = baz.len();
5+
| ^^^^^
6+
|
7+
= note: calls in constant functions are limited to constant functions, tuple structs and tuple variants
8+
9+
error[E0277]: the trait bound `Vec<usize>: ~const IndexMut<usize>` is not satisfied
10+
--> $DIR/issue-94675.rs:9:9
11+
|
12+
LL | self.bar[0] = baz.len();
13+
| ^^^^^^^^^^^ vector indices are of type `usize` or ranges of `usize`
14+
|
15+
= help: the trait `~const IndexMut<usize>` is not implemented for `Vec<usize>`
16+
note: the trait `IndexMut<usize>` is implemented for `Vec<usize>`, but that implementation is not `const`
17+
--> $DIR/issue-94675.rs:9:9
18+
|
19+
LL | self.bar[0] = baz.len();
20+
| ^^^^^^^^^^^
21+
22+
error[E0015]: cannot call non-const operator in constant functions
23+
--> $DIR/issue-94675.rs:9:9
24+
|
25+
LL | self.bar[0] = baz.len();
26+
| ^^^^^^^^^^^
27+
|
28+
note: impl defined here, but it is not `const`
29+
--> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
30+
|
31+
LL | impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
32+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
33+
= note: calls in constant functions are limited to constant functions, tuple structs and tuple variants
34+
35+
error: aborting due to 3 previous errors
36+
37+
Some errors have detailed explanations: E0015, E0277.
38+
For more information about an error, try `rustc --explain E0015`.

src/test/ui/issues/issue-87707.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// test for #87707
22
// edition:2018
33
// run-fail
4+
// exec-env:RUST_BACKTRACE=0
45
// check-run-results
56

67
use std::sync::Once;
+2-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
thread 'main' panicked at 'Here Once instance is poisoned.', $DIR/issue-87707.rs:12:24
1+
thread 'main' panicked at 'Here Once instance is poisoned.', $DIR/issue-87707.rs:13:24
22
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
3-
thread 'main' panicked at 'Once instance has previously been poisoned', $DIR/issue-87707.rs:14:7
3+
thread 'main' panicked at 'Once instance has previously been poisoned', $DIR/issue-87707.rs:15:7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#![feature(rustc_attrs)]
2+
3+
trait Foo<A> {
4+
fn foo(self);
5+
}
6+
7+
#[rustc_on_unimplemented = "an impl did not match: {A} {B} {C}"]
8+
impl<A, B, C> Foo<A> for (A, B, C) {
9+
fn foo(self) {}
10+
}
11+
12+
fn main() {
13+
Foo::<usize>::foo((1i32, 1i32, 1i32));
14+
//~^ ERROR the trait bound `(i32, i32, i32): Foo<usize>` is not satisfied
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
error[E0277]: the trait bound `(i32, i32, i32): Foo<usize>` is not satisfied
2+
--> $DIR/impl-substs.rs:13:23
3+
|
4+
LL | Foo::<usize>::foo((1i32, 1i32, 1i32));
5+
| ----------------- ^^^^^^^^^^^^^^^^^^ an impl did not match: usize _ _
6+
| |
7+
| required by a bound introduced by this call
8+
|
9+
= help: the trait `Foo<usize>` is not implemented for `(i32, i32, i32)`
10+
11+
error: aborting due to previous error
12+
13+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)