Skip to content

Commit f5a75ff

Browse files
committed
Reject escaping generic params in the type of assoc const bindings
1 parent 6ff7a2c commit f5a75ff

File tree

5 files changed

+182
-4
lines changed

5 files changed

+182
-4
lines changed

compiler/rustc_hir_analysis/messages.ftl

+14
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,20 @@ hir_analysis_only_current_traits_primitive = only traits defined in the current
289289
290290
hir_analysis_only_current_traits_ty = `{$ty}` is not defined in the current crate
291291
292+
hir_analysis_param_in_ty_of_assoc_const_binding =
293+
the type of the associated constant `{$assoc_const}` must not depend on {$synthetic ->
294+
[true] `impl Trait`
295+
*[false] generic parameters
296+
}
297+
.label = its type must not depend on {$synthetic ->
298+
[true] `impl Trait`
299+
*[false] the {$param_def_kind} `{$param_name}`
300+
}
301+
.param_defined_here_label = {$synthetic ->
302+
[true] the `impl Trait` is specified here
303+
*[false] the {$param_def_kind} `{$param_name}` is defined here
304+
}
305+
292306
hir_analysis_paren_sugar_attribute = the `#[rustc_paren_sugar]` attribute is a temporary means of controlling which traits can use parenthetical notation
293307
.help = add `#![feature(unboxed_closures)]` to the crate attributes to use it
294308

compiler/rustc_hir_analysis/src/collect/type_of.rs

+81-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
use std::ops::ControlFlow;
2+
3+
use rustc_data_structures::fx::FxIndexSet;
14
use rustc_errors::{Applicability, StashKey};
25
use rustc_hir as hir;
36
use rustc_hir::def_id::{DefId, LocalDefId};
@@ -7,7 +10,8 @@ use rustc_middle::ty::print::with_forced_trimmed_paths;
710
use rustc_middle::ty::util::IntTypeExt;
811
use rustc_middle::ty::{self, ImplTraitInTraitData, IsSuggestable, Ty, TyCtxt, TypeVisitableExt};
912
use rustc_span::symbol::Ident;
10-
use rustc_span::{Span, DUMMY_SP};
13+
use rustc_span::{ErrorGuaranteed, Span, Symbol, DUMMY_SP};
14+
use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
1115

1216
use super::bad_placeholder;
1317
use super::ItemCtxt;
@@ -66,10 +70,23 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> {
6670
.expect("const parameter types cannot be generic");
6771
}
6872

69-
Node::TypeBinding(&TypeBinding { hir_id, .. }) => {
70-
// FIXME(fmease): Reject “escaping” early-bound generic parameters.
73+
Node::TypeBinding(&TypeBinding { hir_id, ident, .. }) => {
74+
let ty = tcx.type_of_assoc_const_binding(hir_id);
75+
76+
// We can't possibly catch this in the resolver, therefore we need to handle it here.
77+
// FIXME(const_generics): Support generic const generics.
78+
let Some(ty) = ty.no_bound_vars() else {
79+
let reported = report_overly_generic_assoc_const_binding_type(
80+
tcx,
81+
ident,
82+
ty.skip_binder().skip_binder(),
83+
hir_id,
84+
);
85+
return Ty::new_error(tcx, reported);
86+
};
87+
7188
// FIXME(fmease): Reject escaping late-bound vars.
72-
return tcx.type_of_assoc_const_binding(hir_id).skip_binder().skip_binder();
89+
return ty.skip_binder();
7390
}
7491

7592
// This match arm is for when the def_id appears in a GAT whose
@@ -290,6 +307,66 @@ pub(super) fn type_of_assoc_const_binding<'tcx>(
290307
ty::EarlyBinder::bind(ty::Binder::dummy(Ty::new_error(tcx, reported)))
291308
}
292309

310+
fn report_overly_generic_assoc_const_binding_type<'tcx>(
311+
tcx: TyCtxt<'tcx>,
312+
assoc_const: Ident,
313+
ty: Ty<'tcx>,
314+
hir_id: HirId,
315+
) -> ErrorGuaranteed {
316+
let mut collector = GenericParamCollector { params: Default::default() };
317+
ty.visit_with(&mut collector);
318+
319+
let mut reported = None;
320+
321+
let body_owner = tcx.hir().enclosing_body_owner(hir_id);
322+
let generics = tcx.generics_of(body_owner);
323+
for (param_index, param_name) in collector.params {
324+
let param_def = generics.param_at(param_index as _, tcx);
325+
reported.get_or_insert(tcx.dcx().emit_err(crate::errors::ParamInTyOfAssocConstBinding {
326+
span: assoc_const.span,
327+
assoc_const,
328+
param_name,
329+
param_def_kind: tcx.def_descr(param_def.def_id),
330+
synthetic: param_def.kind.is_synthetic(),
331+
param_defined_here_label: tcx.def_ident_span(param_def.def_id).unwrap(),
332+
}));
333+
}
334+
335+
struct GenericParamCollector {
336+
params: FxIndexSet<(u32, Symbol)>,
337+
}
338+
339+
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GenericParamCollector {
340+
type BreakTy = !;
341+
342+
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
343+
if let ty::Param(param) = ty.kind() {
344+
self.params.insert((param.index, param.name));
345+
return ControlFlow::Continue(());
346+
}
347+
ty.super_visit_with(self)
348+
}
349+
350+
fn visit_region(&mut self, re: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
351+
if let ty::ReEarlyParam(param) = re.kind() {
352+
self.params.insert((param.index, param.name));
353+
return ControlFlow::Continue(());
354+
}
355+
ControlFlow::Continue(())
356+
}
357+
358+
fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
359+
if let ty::ConstKind::Param(param) = ct.kind() {
360+
self.params.insert((param.index, param.name));
361+
return ControlFlow::Continue(());
362+
}
363+
ct.super_visit_with(self)
364+
}
365+
}
366+
367+
reported.unwrap_or_else(|| bug!("failed to find gen params in ty"))
368+
}
369+
293370
fn get_path_containing_arg_in_pat<'hir>(
294371
pat: &'hir hir::Pat<'hir>,
295372
arg_id: HirId,

compiler/rustc_hir_analysis/src/errors.rs

+14
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,20 @@ pub struct AssocTypeBindingNotAllowed {
254254
pub fn_trait_expansion: Option<ParenthesizedFnTraitExpansion>,
255255
}
256256

257+
#[derive(Diagnostic)]
258+
#[diag(hir_analysis_param_in_ty_of_assoc_const_binding)]
259+
pub(crate) struct ParamInTyOfAssocConstBinding {
260+
#[primary_span]
261+
#[label]
262+
pub span: Span,
263+
pub assoc_const: Ident,
264+
pub param_name: Symbol,
265+
pub param_def_kind: &'static str,
266+
pub synthetic: bool,
267+
#[label(hir_analysis_param_defined_here_label)]
268+
pub param_defined_here_label: Span,
269+
}
270+
257271
#[derive(Subdiagnostic)]
258272
#[help(hir_analysis_parenthesized_fn_trait_expansion)]
259273
pub struct ParenthesizedFnTraitExpansion {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Regression test for issue #108271.
2+
// Detect and reject generic params in the type of assoc consts used in an equality bound.
3+
#![feature(associated_const_equality)]
4+
5+
trait Trait<'a, T: 'a, const N: usize> {
6+
const K: &'a [T; N];
7+
}
8+
9+
fn take0<'r, A: 'r, const Q: usize>(_: impl Trait<'r, A, Q, K = { loop {} }>) {}
10+
//~^ ERROR the type of the associated constant `K` must not depend on generic parameters
11+
//~| NOTE its type must not depend on the lifetime parameter `'r`
12+
//~| NOTE the lifetime parameter `'r` is defined here
13+
//~| ERROR the type of the associated constant `K` must not depend on generic parameters
14+
//~| NOTE its type must not depend on the type parameter `A`
15+
//~| NOTE the type parameter `A` is defined here
16+
//~| ERROR the type of the associated constant `K` must not depend on generic parameters
17+
//~| NOTE its type must not depend on the const parameter `Q`
18+
//~| NOTE the const parameter `Q` is defined here
19+
20+
trait Project {
21+
const SELF: Self;
22+
}
23+
24+
fn take1(_: impl Project<SELF = {}>) {}
25+
//~^ ERROR the type of the associated constant `SELF` must not depend on `impl Trait`
26+
//~| NOTE its type must not depend on `impl Trait`
27+
//~| NOTE the `impl Trait` is specified here
28+
29+
fn take2<P: Project<SELF = {}>>(_: P) {}
30+
//~^ ERROR the type of the associated constant `SELF` must not depend on generic parameters
31+
//~| NOTE its type must not depend on the type parameter `P`
32+
//~| NOTE the type parameter `P` is defined here
33+
34+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
error: the type of the associated constant `K` must not depend on generic parameters
2+
--> $DIR/assoc-const-eq-param-in-ty.rs:9:61
3+
|
4+
LL | fn take0<'r, A: 'r, const Q: usize>(_: impl Trait<'r, A, Q, K = { loop {} }>) {}
5+
| -- the lifetime parameter `'r` is defined here ^ its type must not depend on the lifetime parameter `'r`
6+
7+
error: the type of the associated constant `K` must not depend on generic parameters
8+
--> $DIR/assoc-const-eq-param-in-ty.rs:9:61
9+
|
10+
LL | fn take0<'r, A: 'r, const Q: usize>(_: impl Trait<'r, A, Q, K = { loop {} }>) {}
11+
| - the type parameter `A` is defined here ^ its type must not depend on the type parameter `A`
12+
13+
error: the type of the associated constant `K` must not depend on generic parameters
14+
--> $DIR/assoc-const-eq-param-in-ty.rs:9:61
15+
|
16+
LL | fn take0<'r, A: 'r, const Q: usize>(_: impl Trait<'r, A, Q, K = { loop {} }>) {}
17+
| - ^ its type must not depend on the const parameter `Q`
18+
| |
19+
| the const parameter `Q` is defined here
20+
21+
error: the type of the associated constant `SELF` must not depend on `impl Trait`
22+
--> $DIR/assoc-const-eq-param-in-ty.rs:24:26
23+
|
24+
LL | fn take1(_: impl Project<SELF = {}>) {}
25+
| -------------^^^^------
26+
| | |
27+
| | its type must not depend on `impl Trait`
28+
| the `impl Trait` is specified here
29+
30+
error: the type of the associated constant `SELF` must not depend on generic parameters
31+
--> $DIR/assoc-const-eq-param-in-ty.rs:29:21
32+
|
33+
LL | fn take2<P: Project<SELF = {}>>(_: P) {}
34+
| - ^^^^ its type must not depend on the type parameter `P`
35+
| |
36+
| the type parameter `P` is defined here
37+
38+
error: aborting due to 5 previous errors
39+

0 commit comments

Comments
 (0)