Skip to content

Commit fbb8e34

Browse files
authored
Merge pull request #23179 from ChayimFriedman2/anon-const-params
fix: Fix handling of generic params in anon consts
2 parents e6f6dc2 + 26bd558 commit fbb8e34

14 files changed

Lines changed: 222 additions & 251 deletions

File tree

‎src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,16 @@ pub(crate) fn path_to_const<'a, 'db>(
350350
Ok(Const::new_unevaluated(interner, UnevaluatedConst { def: konst.into(), args }))
351351
}
352352

353+
/// `forbid_params_after` and `allow_anon_const_using_generic_params` fill a similar role, but are not the same.
354+
///
355+
/// `forbid_params_after` is only respected if an anon const is *not* created, that is, we directly resolve to a const param.
356+
/// `allow_anon_const_using_generic_params` is only respected if an anon const *is* created.
357+
///
358+
/// For example, inside types, you are allowed to refer to const params in bare paths (but might be forbidden from referring
359+
/// to *some*, in param defaults), but not allowed to do so in anon consts (e.g. `{ {}; N }` is forbidden, because it creates
360+
/// an anon const). Inside field defaults, you are allowed to refer to them even inside anon consts.
361+
///
362+
/// There's also `generic_const_exprs`, `min_generic_const_args`, and `generic_const_args`, all of which we don't implement yet.
353363
pub(crate) fn create_anon_const<'a, 'db>(
354364
interner: DbInterner<'db>,
355365
owner: ExpressionStoreOwnerId,
@@ -361,6 +371,7 @@ pub(crate) fn create_anon_const<'a, 'db>(
361371
create_var: Option<&mut dyn FnMut(Span) -> Const<'db>>,
362372
lowering_mode: LoweringMode,
363373
forbid_params_after: Option<u32>,
374+
allow_anon_const_using_generic_params: bool,
364375
) -> Result<Const<'db>, CreateConstError<'db>> {
365376
let mut expr = &store[expr_id];
366377
if let Expr::Block { statements, tail: Some(tail), .. } = expr
@@ -396,18 +407,17 @@ pub(crate) fn create_anon_const<'a, 'db>(
396407
return Err(CreateConstError::AnonConstInterningDisabled);
397408
};
398409

399-
let allow_using_generic_params = forbid_params_after.is_none();
400410
let konst = AnonConstId::new(
401411
interner.db,
402412
AnonConstLoc {
403413
owner,
404414
expr: expr_id,
405415
ty: StoredEarlyBinder::bind(expected_ty.store()),
406-
allow_using_generic_params,
416+
allow_using_generic_params: allow_anon_const_using_generic_params,
407417
},
408418
token,
409419
);
410-
let args = if allow_using_generic_params {
420+
let args = if allow_anon_const_using_generic_params {
411421
GenericArgs::identity_for_item(interner, owner.generic_def(interner.db).into())
412422
} else {
413423
GenericArgs::empty()

‎src/tools/rust-analyzer/crates/hir-ty/src/infer.rs‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1981,12 +1981,7 @@ impl<'db> InferenceContext<'db> {
19811981
})
19821982
}
19831983

1984-
pub(crate) fn create_anon_const(
1985-
&mut self,
1986-
expr: ExprId,
1987-
expected_ty: Ty<'db>,
1988-
allow_using_generic_params: bool,
1989-
) -> Const<'db> {
1984+
pub(crate) fn create_anon_const(&mut self, expr: ExprId, expected_ty: Ty<'db>) -> Const<'db> {
19901985
never!(expected_ty.has_infer(), "cannot have infer vars in an anon const's ty");
19911986
let konst = create_anon_const(
19921987
self.interner(),
@@ -1998,7 +1993,11 @@ impl<'db> InferenceContext<'db> {
19981993
&|| self.generics(),
19991994
Some(&mut |span| self.table.next_const_var(span)),
20001995
self.lowering_mode,
2001-
(!(allow_using_generic_params && self.allow_using_generic_params)).then_some(0),
1996+
(!self.allow_using_generic_params).then_some(0),
1997+
// The situation around body anon consts using generic params is complicated.
1998+
// rustc disallows them all, except for array repeat expressions. However in another place even repeat exprs
1999+
// are disallowed, so in practice they cause an error.
2000+
false,
20022001
);
20032002

20042003
if let Ok(konst) = konst

‎src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1309,7 +1309,7 @@ impl<'db> InferenceContext<'db> {
13091309
expr: ExprId,
13101310
) -> Ty<'db> {
13111311
let interner = self.interner();
1312-
let count_ct = self.create_anon_const(count, self.types.types.usize, true);
1312+
let count_ct = self.create_anon_const(count, self.types.types.usize);
13131313
let count = self.table.try_structurally_resolve_const(count.into(), count_ct);
13141314

13151315
let uty = match expected {

‎src/tools/rust-analyzer/crates/hir-ty/src/lower.rs‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -450,14 +450,20 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> {
450450
self.lower_ty_ext(type_ref).0
451451
}
452452

453-
pub(crate) fn lower_const(&mut self, const_ref: ConstRef, const_type: Ty<'db>) -> Const<'db> {
454-
self.lower_expr_as_const(const_ref.expr, const_type)
453+
pub(crate) fn lower_const(
454+
&mut self,
455+
const_ref: ConstRef,
456+
const_type: Ty<'db>,
457+
allow_anon_const_using_generic_params: bool,
458+
) -> Const<'db> {
459+
self.lower_expr_as_const(const_ref.expr, const_type, allow_anon_const_using_generic_params)
455460
}
456461

457462
pub(crate) fn lower_expr_as_const(
458463
&mut self,
459464
expr_id: ExprId,
460465
const_type: Ty<'db>,
466+
allow_anon_const_using_generic_params: bool,
461467
) -> Const<'db> {
462468
#[expect(clippy::manual_map, reason = "a `map()` here generates a borrowck error")]
463469
let create_var = match &mut self.infer_vars {
@@ -477,6 +483,7 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> {
477483
create_var,
478484
self.interning_mode,
479485
self.forbid_params_after,
486+
allow_anon_const_using_generic_params,
480487
);
481488

482489
if let Ok(konst) = konst
@@ -603,7 +610,7 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> {
603610
}
604611
TypeRef::Array(array) => {
605612
let inner_ty = self.lower_ty(array.ty);
606-
let const_len = self.lower_const(array.len, self.types.types.usize);
613+
let const_len = self.lower_const(array.len, self.types.types.usize, false);
607614
Ty::new_array_with_const_len(interner, inner_ty, const_len)
608615
}
609616
&TypeRef::Slice(inner) => {
@@ -729,9 +736,12 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> {
729736
fn lower_pattern_type(&mut self, pat: PatId, ty: Ty<'db>) -> Option<Pattern<'db>> {
730737
let pat_kind = match self.store[pat] {
731738
hir_def::hir::Pat::Range { start: Some(start), end: Some(end), range_type: _ } => {
739+
// rustc allows using generic params in pattern types.
740+
// In practice this does not matter since this feature is internal and I didn't find a way to actually use generic params,
741+
// but it doesn't matter so...
732742
rustc_type_ir::PatternKind::Range {
733-
start: self.lower_expr_as_const(start, ty),
734-
end: self.lower_expr_as_const(end, ty),
743+
start: self.lower_expr_as_const(start, ty, true),
744+
end: self.lower_expr_as_const(end, ty, true),
735745
}
736746
}
737747
hir_def::hir::Pat::NotNull => rustc_type_ir::PatternKind::NotNull,
@@ -1975,7 +1985,7 @@ pub(crate) fn field_types_with_diagnostics<'db>(
19751985
);
19761986
for (field_id, field_data) in var_data.fields().iter() {
19771987
let ty = ctx.lower_ty(field_data.type_ref);
1978-
let default = field_data.default_value.map(|default| ctx.lower_const(default, ty));
1988+
let default = field_data.default_value.map(|default| ctx.lower_const(default, ty, true));
19791989
res.insert(
19801990
field_id,
19811991
FieldType {
@@ -3012,7 +3022,7 @@ pub(crate) fn generic_defaults_with_diagnostics<'db>(
30123022
GenericParamDataRef::ConstParamData(p) => {
30133023
let val = p.default.map(|c| {
30143024
let param_ty = ctx.lower_ty(p.ty);
3015-
let c = ctx.lower_const(c, param_ty);
3025+
let c = ctx.lower_const(c, param_ty, false);
30163026
GenericArg::from(c).store()
30173027
});
30183028
val.map(StoredEarlyBinder::bind)

‎src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -743,7 +743,7 @@ impl<'a, 'b, 'db> PathLoweringContext<'a, 'b, 'db> {
743743
};
744744
self.ctx
745745
.ctx
746-
.lower_const(konst, const_param_ty(self.ctx.ctx.db, const_id))
746+
.lower_const(konst, const_param_ty(self.ctx.ctx.db, const_id), false)
747747
.into()
748748
}
749749
_ => unreachable!("unmatching param kinds were passed to `provided_kind()`"),

‎src/tools/rust-analyzer/crates/hir-ty/src/method_resolution/confirm.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ impl<'a, 'db> ConfirmContext<'a, 'db> {
404404
unreachable!("non-const param ID for const param");
405405
};
406406
let const_ty = self.ctx.db.const_param_ty(const_id);
407-
self.ctx.create_anon_const(konst.expr, const_ty, false).into()
407+
self.ctx.create_anon_const(konst.expr, const_ty).into()
408408
}
409409
_ => unreachable!("unmatching param kinds were passed to `provided_kind()`"),
410410
}

0 commit comments

Comments
 (0)