Skip to content

Commit 8051d07

Browse files
committed
Auto merge of rust-lang#125915 - camelid:const-arg-refactor, r=BoxyUwU
Represent type-level consts with new-and-improved `hir::ConstArg` ### Summary This is a step toward `min_generic_const_exprs`. We now represent all const generic arguments using an enum that differentiates between const *paths* (temporarily just bare const params) and arbitrary anon consts that may perform computations. This will enable us to cleanly implement the `min_generic_const_args` plan of allowing the use of generics in paths used as const args, while disallowing their use in arbitrary anon consts. Here is a summary of the salient aspects of this change: - Add `current_def_id_parent` to `LoweringContext` This is needed to track anon const parents properly once we implement `ConstArgKind::Path` (which requires moving anon const def-creation outside of `DefCollector`). - Create `hir::ConstArgKind` enum with `Path` and `Anon` variants. Use it in the existing `hir::ConstArg` struct, replacing the previous `hir::AnonConst` field. - Use `ConstArg` for all instances of const args. Specifically, use it instead of `AnonConst` for assoc item constraints, array lengths, and const param defaults. - Some `ast::AnonConst`s now have their `DefId`s created in rustc_ast_lowering rather than `DefCollector`. This is because in some cases they will end up becoming a `ConstArgKind::Path` instead, which has no `DefId`. We have to solve this in a hacky way where we guess whether the `AnonConst` could end up as a path const since we can't know for sure until after name resolution (`N` could refer to a free const or a nullary struct). If it has no chance as being a const param, then we create a `DefId` in `DefCollector` -- otherwise we decide during ast_lowering. This will have to be updated once all path consts use `ConstArgKind::Path`. - We explicitly use `ConstArgHasType` for array lengths, rather than implicitly relying on anon const type feeding -- this is due to the addition of `ConstArgKind::Path`. - Some tests have their outputs changed, but the changes are for the most part minor (including removing duplicate or almost-duplicate errors). One test now ICEs, but it is for an incomplete, unstable feature and is now tracked at rust-lang#127009. ### Followup items post-merge - Use `ConstArgKind::Path` for all const paths, not just const params. - Fix (no github dont close this issue) rust-lang#127009 - If a path in generic args doesn't resolve as a type, try to resolve as a const instead (do this in rustc_resolve). Then remove the special-casing from `rustc_ast_lowering`, so that all params will automatically be lowered as `ConstArgKind::Path`. - (?) Consider making `const_evaluatable_unchecked` a hard error, or at least trying it in crater r? `@BoxyUwU`
2 parents b0209dc + f2c1265 commit 8051d07

File tree

7 files changed

+71
-31
lines changed

7 files changed

+71
-31
lines changed

clippy_lints/src/large_stack_arrays.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,12 @@ fn might_be_expanded<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) -> bool {
106106
///
107107
/// This is a fail-safe to a case where even the `is_from_proc_macro` is unable to determain the
108108
/// correct result.
109-
fn repeat_expr_might_be_expanded<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) -> bool {
110-
let ExprKind::Repeat(_, ArrayLen::Body(anon_const)) = expr.kind else {
109+
fn repeat_expr_might_be_expanded<'tcx>(expr: &Expr<'tcx>) -> bool {
110+
let ExprKind::Repeat(_, ArrayLen::Body(len_ct)) = expr.kind else {
111111
return false;
112112
};
113-
let len_span = cx.tcx.def_span(anon_const.def_id);
114-
!expr.span.contains(len_span)
113+
!expr.span.contains(len_ct.span())
115114
}
116115

117-
expr.span.from_expansion() || is_from_proc_macro(cx, expr) || repeat_expr_might_be_expanded(cx, expr)
116+
expr.span.from_expansion() || is_from_proc_macro(cx, expr) || repeat_expr_might_be_expanded(expr)
118117
}

clippy_lints/src/trailing_empty_array.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_help;
22
use clippy_utils::has_repr_attr;
33
use rustc_hir::{Item, ItemKind};
44
use rustc_lint::{LateContext, LateLintPass};
5-
use rustc_middle::ty::Const;
5+
use rustc_middle::ty::{Const, FeedConstTy};
66
use rustc_session::declare_lint_pass;
77

88
declare_clippy_lint! {
@@ -53,14 +53,14 @@ impl<'tcx> LateLintPass<'tcx> for TrailingEmptyArray {
5353
}
5454
}
5555

56-
fn is_struct_with_trailing_zero_sized_array(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
56+
fn is_struct_with_trailing_zero_sized_array<'tcx>(cx: &LateContext<'tcx>, item: &Item<'tcx>) -> bool {
5757
if let ItemKind::Struct(data, _) = &item.kind
5858
// First check if last field is an array
5959
&& let Some(last_field) = data.fields().last()
6060
&& let rustc_hir::TyKind::Array(_, rustc_hir::ArrayLen::Body(length)) = last_field.ty.kind
6161

6262
// Then check if that array is zero-sized
63-
&& let length = Const::from_anon_const(cx.tcx, length.def_id)
63+
&& let length = Const::from_const_arg(cx.tcx, length, FeedConstTy::No)
6464
&& let length = length.try_eval_target_usize(cx.tcx, cx.param_env)
6565
&& let Some(length) = length
6666
{

clippy_lints/src/utils/author.rs

+21-7
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ use clippy_utils::{get_attr, higher};
55
use rustc_ast::ast::{LitFloatType, LitKind};
66
use rustc_ast::LitIntType;
77
use rustc_data_structures::fx::FxHashMap;
8-
use rustc_hir as hir;
98
use rustc_hir::{
10-
ArrayLen, BindingMode, CaptureBy, Closure, ClosureKind, CoroutineKind, ExprKind, FnRetTy, HirId, Lit, PatKind,
11-
QPath, StmtKind, TyKind,
9+
self as hir, ArrayLen, BindingMode, CaptureBy, Closure, ClosureKind, ConstArg, ConstArgKind, CoroutineKind,
10+
ExprKind, FnRetTy, HirId, Lit, PatKind, QPath, StmtKind, TyKind,
1211
};
1312
use rustc_lint::{LateContext, LateLintPass, LintContext};
1413
use rustc_session::declare_lint_pass;
@@ -270,6 +269,21 @@ impl<'a, 'tcx> PrintVisitor<'a, 'tcx> {
270269
}
271270
}
272271

272+
fn const_arg(&self, const_arg: &Binding<&ConstArg<'_>>) {
273+
match const_arg.value.kind {
274+
ConstArgKind::Path(ref qpath) => {
275+
bind!(self, qpath);
276+
chain!(self, "let ConstArgKind::Path(ref {qpath}) = {const_arg}.kind");
277+
self.qpath(qpath);
278+
},
279+
ConstArgKind::Anon(anon_const) => {
280+
bind!(self, anon_const);
281+
chain!(self, "let ConstArgKind::Anon({anon_const}) = {const_arg}.kind");
282+
self.body(field!(anon_const.body));
283+
},
284+
}
285+
}
286+
273287
fn lit(&self, lit: &Binding<&Lit>) {
274288
let kind = |kind| chain!(self, "let LitKind::{kind} = {lit}.node");
275289
macro_rules! kind {
@@ -602,10 +616,10 @@ impl<'a, 'tcx> PrintVisitor<'a, 'tcx> {
602616
self.expr(value);
603617
match length.value {
604618
ArrayLen::Infer(..) => chain!(self, "let ArrayLen::Infer(..) = length"),
605-
ArrayLen::Body(anon_const) => {
606-
bind!(self, anon_const);
607-
chain!(self, "let ArrayLen::Body({anon_const}) = {length}");
608-
self.body(field!(anon_const.body));
619+
ArrayLen::Body(const_arg) => {
620+
bind!(self, const_arg);
621+
chain!(self, "let ArrayLen::Body({const_arg}) = {length}");
622+
self.const_arg(const_arg);
609623
},
610624
}
611625
},

clippy_utils/src/hir_utils.rs

+25-7
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ use rustc_data_structures::fx::FxHasher;
77
use rustc_hir::def::Res;
88
use rustc_hir::MatchSource::TryDesugar;
99
use rustc_hir::{
10-
ArrayLen, AssocItemConstraint, BinOpKind, BindingMode, Block, BodyId, Closure, Expr, ExprField, ExprKind, FnRetTy,
11-
GenericArg, GenericArgs, HirId, HirIdMap, InlineAsmOperand, LetExpr, Lifetime, LifetimeName, Pat, PatField,
12-
PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, Ty, TyKind,
10+
ArrayLen, AssocItemConstraint, BinOpKind, BindingMode, Block, BodyId, Closure, ConstArg, ConstArgKind, Expr,
11+
ExprField, ExprKind, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, InlineAsmOperand, LetExpr, Lifetime,
12+
LifetimeName, Pat, PatField, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, Ty, TyKind,
1313
};
1414
use rustc_lexer::{tokenize, TokenKind};
1515
use rustc_lint::LateContext;
@@ -227,7 +227,7 @@ impl HirEqInterExpr<'_, '_, '_> {
227227
pub fn eq_array_length(&mut self, left: ArrayLen<'_>, right: ArrayLen<'_>) -> bool {
228228
match (left, right) {
229229
(ArrayLen::Infer(..), ArrayLen::Infer(..)) => true,
230-
(ArrayLen::Body(l_ct), ArrayLen::Body(r_ct)) => self.eq_body(l_ct.body, r_ct.body),
230+
(ArrayLen::Body(l_ct), ArrayLen::Body(r_ct)) => self.eq_const_arg(l_ct, r_ct),
231231
(_, _) => false,
232232
}
233233
}
@@ -411,14 +411,25 @@ impl HirEqInterExpr<'_, '_, '_> {
411411

412412
fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
413413
match (left, right) {
414-
(GenericArg::Const(l), GenericArg::Const(r)) => self.eq_body(l.value.body, r.value.body),
414+
(GenericArg::Const(l), GenericArg::Const(r)) => self.eq_const_arg(l, r),
415415
(GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
416416
(GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty),
417417
(GenericArg::Infer(l_inf), GenericArg::Infer(r_inf)) => self.eq_ty(&l_inf.to_ty(), &r_inf.to_ty()),
418418
_ => false,
419419
}
420420
}
421421

422+
fn eq_const_arg(&mut self, left: &ConstArg<'_>, right: &ConstArg<'_>) -> bool {
423+
match (&left.kind, &right.kind) {
424+
(ConstArgKind::Path(l_p), ConstArgKind::Path(r_p)) => self.eq_qpath(l_p, r_p),
425+
(ConstArgKind::Anon(l_an), ConstArgKind::Anon(r_an)) => self.eq_body(l_an.body, r_an.body),
426+
// Use explicit match for now since ConstArg is undergoing flux.
427+
(ConstArgKind::Path(..), ConstArgKind::Anon(..)) | (ConstArgKind::Anon(..), ConstArgKind::Path(..)) => {
428+
false
429+
},
430+
}
431+
}
432+
422433
fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
423434
left.res == right.res
424435
}
@@ -1123,7 +1134,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
11231134
pub fn hash_array_length(&mut self, length: ArrayLen<'_>) {
11241135
match length {
11251136
ArrayLen::Infer(..) => {},
1126-
ArrayLen::Body(anon_const) => self.hash_body(anon_const.body),
1137+
ArrayLen::Body(ct) => self.hash_const_arg(ct),
11271138
}
11281139
}
11291140

@@ -1134,12 +1145,19 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
11341145
self.maybe_typeck_results = old_maybe_typeck_results;
11351146
}
11361147

1148+
fn hash_const_arg(&mut self, const_arg: &ConstArg<'_>) {
1149+
match &const_arg.kind {
1150+
ConstArgKind::Path(path) => self.hash_qpath(path),
1151+
ConstArgKind::Anon(anon) => self.hash_body(anon.body),
1152+
}
1153+
}
1154+
11371155
fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
11381156
for arg in arg_list {
11391157
match *arg {
11401158
GenericArg::Lifetime(l) => self.hash_lifetime(l),
11411159
GenericArg::Type(ty) => self.hash_ty(ty),
1142-
GenericArg::Const(ref ca) => self.hash_body(ca.value.body),
1160+
GenericArg::Const(ref ca) => self.hash_const_arg(ca),
11431161
GenericArg::Infer(ref inf) => self.hash_ty(&inf.to_ty()),
11441162
}
11451163
}

clippy_utils/src/lib.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,11 @@ use rustc_hir::hir_id::{HirIdMap, HirIdSet};
102102
use rustc_hir::intravisit::{walk_expr, FnKind, Visitor};
103103
use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk};
104104
use rustc_hir::{
105-
self as hir, def, Arm, ArrayLen, BindingMode, Block, BlockCheckMode, Body, ByRef, Closure, ConstContext,
106-
Destination, Expr, ExprField, ExprKind, FnDecl, FnRetTy, GenericArgs, HirId, Impl, ImplItem, ImplItemKind,
107-
ImplItemRef, Item, ItemKind, LangItem, LetStmt, MatchSource, Mutability, Node, OwnerId, OwnerNode, Param, Pat,
108-
PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, TraitItem, TraitItemKind, TraitItemRef, TraitRef,
109-
TyKind, UnOp,
105+
self as hir, def, Arm, ArrayLen, BindingMode, Block, BlockCheckMode, Body, ByRef, Closure, ConstArgKind,
106+
ConstContext, Destination, Expr, ExprField, ExprKind, FnDecl, FnRetTy, GenericArgs, HirId, Impl, ImplItem,
107+
ImplItemKind, ImplItemRef, Item, ItemKind, LangItem, LetStmt, MatchSource, Mutability, Node, OwnerId, OwnerNode,
108+
Param, Pat, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, TraitItem, TraitItemKind, TraitItemRef,
109+
TraitRef, TyKind, UnOp,
110110
};
111111
use rustc_lexer::{tokenize, TokenKind};
112112
use rustc_lint::{LateContext, Level, Lint, LintContext};
@@ -904,7 +904,8 @@ pub fn is_default_equivalent(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
904904
},
905905
ExprKind::Tup(items) | ExprKind::Array(items) => items.iter().all(|x| is_default_equivalent(cx, x)),
906906
ExprKind::Repeat(x, ArrayLen::Body(len)) => {
907-
if let ExprKind::Lit(const_lit) = cx.tcx.hir().body(len.body).value.kind
907+
if let ConstArgKind::Anon(anon_const) = len.kind
908+
&& let ExprKind::Lit(const_lit) = cx.tcx.hir().body(anon_const.body).value.kind
908909
&& let LitKind::Int(v, _) = const_lit.node
909910
&& v <= 32
910911
&& is_default_equivalent(cx, x)
@@ -933,7 +934,8 @@ fn is_default_equivalent_from(cx: &LateContext<'_>, from_func: &Expr<'_>, arg: &
933934
}) => return sym.is_empty() && is_path_lang_item(cx, ty, LangItem::String),
934935
ExprKind::Array([]) => return is_path_diagnostic_item(cx, ty, sym::Vec),
935936
ExprKind::Repeat(_, ArrayLen::Body(len)) => {
936-
if let ExprKind::Lit(const_lit) = cx.tcx.hir().body(len.body).value.kind
937+
if let ConstArgKind::Anon(anon_const) = len.kind
938+
&& let ExprKind::Lit(const_lit) = cx.tcx.hir().body(anon_const.body).value.kind
937939
&& let LitKind::Int(v, _) = const_lit.node
938940
{
939941
return v == 0 && is_path_diagnostic_item(cx, ty, sym::Vec);

tests/ui/author/repeat.stdout

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
if let ExprKind::Repeat(value, length) = expr.kind
22
&& let ExprKind::Lit(ref lit) = value.kind
33
&& let LitKind::Int(1, LitIntType::Unsigned(UintTy::U8)) = lit.node
4-
&& let ArrayLen::Body(anon_const) = length
4+
&& let ArrayLen::Body(const_arg) = length
5+
&& let ConstArgKind::Anon(anon_const) = const_arg.kind
56
&& expr1 = &cx.tcx.hir().body(anon_const.body).value
67
&& let ExprKind::Lit(ref lit1) = expr1.kind
78
&& let LitKind::Int(5, LitIntType::Unsuffixed) = lit1.node

tests/ui/min_ident_chars.stderr

+7-1
Original file line numberDiff line numberDiff line change
@@ -193,5 +193,11 @@ error: this ident consists of a single char
193193
LL | fn wrong_pythagoras(a: f32, b: f32) -> f32 {
194194
| ^
195195

196-
error: aborting due to 32 previous errors
196+
error: this ident consists of a single char
197+
--> tests/ui/min_ident_chars.rs:93:41
198+
|
199+
LL | struct Array<T, const N: usize>([T; N]);
200+
| ^
201+
202+
error: aborting due to 33 previous errors
197203

0 commit comments

Comments
 (0)