Skip to content

Commit ee55202

Browse files
committed
Port #[rustc_legacy_const_generics] to use attribute parser
1 parent 52fda2e commit ee55202

File tree

14 files changed

+225
-187
lines changed

14 files changed

+225
-187
lines changed

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -237,25 +237,27 @@ impl SpanLowerer {
237237
#[extension(trait ResolverAstLoweringExt)]
238238
impl ResolverAstLowering {
239239
fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>> {
240-
if let ExprKind::Path(None, path) = &expr.kind {
241-
// Don't perform legacy const generics rewriting if the path already
242-
// has generic arguments.
243-
if path.segments.last().unwrap().args.is_some() {
244-
return None;
245-
}
240+
let ExprKind::Path(None, path) = &expr.kind else {
241+
return None;
242+
};
246243

247-
if let Res::Def(DefKind::Fn, def_id) = self.partial_res_map.get(&expr.id)?.full_res()? {
248-
// We only support cross-crate argument rewriting. Uses
249-
// within the same crate should be updated to use the new
250-
// const generics style.
251-
if def_id.is_local() {
252-
return None;
253-
}
244+
// Don't perform legacy const generics rewriting if the path already
245+
// has generic arguments.
246+
if path.segments.last().unwrap().args.is_some() {
247+
return None;
248+
}
254249

255-
if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
256-
return v.clone();
257-
}
258-
}
250+
let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
251+
252+
// We only support cross-crate argument rewriting. Uses
253+
// within the same crate should be updated to use the new
254+
// const generics style.
255+
if def_id.is_local() {
256+
return None;
257+
}
258+
259+
if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
260+
return v.clone();
259261
}
260262

261263
None

compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use rustc_ast::{LitIntType, LitKind, MetaItemLit};
2+
13
use super::prelude::*;
24
use super::util::parse_single_integer;
35

@@ -76,3 +78,47 @@ impl<S: Stage> SingleAttributeParser<S> for RustcSimdMonomorphizeLaneLimitParser
7678
Some(AttributeKind::RustcSimdMonomorphizeLaneLimit(cx.parse_limit_int(nv)?))
7779
}
7880
}
81+
82+
pub(crate) struct RustcLegacyConstGenericsParser;
83+
84+
impl<S: Stage> SingleAttributeParser<S> for RustcLegacyConstGenericsParser {
85+
const PATH: &[Symbol] = &[sym::rustc_legacy_const_generics];
86+
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost;
87+
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
88+
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
89+
const TEMPLATE: AttributeTemplate = template!(List: &["N"]);
90+
91+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
92+
let ArgParser::List(meta_items) = args else {
93+
cx.expected_list(cx.attr_span, args);
94+
return None;
95+
};
96+
97+
let mut parsed_indexes = ThinVec::new();
98+
let mut errored = false;
99+
100+
for possible_index in meta_items.mixed() {
101+
if let MetaItemOrLitParser::Lit(MetaItemLit {
102+
kind: LitKind::Int(index, LitIntType::Unsuffixed),
103+
..
104+
}) = possible_index
105+
{
106+
parsed_indexes.push((index.0 as usize, possible_index.span()));
107+
} else {
108+
cx.expected_integer_literal(possible_index.span());
109+
errored = true;
110+
}
111+
}
112+
if errored {
113+
return None;
114+
} else if parsed_indexes.is_empty() {
115+
cx.expected_at_least_one_argument(args.span()?);
116+
return None;
117+
}
118+
119+
Some(AttributeKind::RustcLegacyConstGenerics {
120+
fn_indexes: parsed_indexes,
121+
attr_span: cx.attr_span,
122+
})
123+
}
124+
}

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,9 @@ use crate::attributes::proc_macro_attrs::{
5959
use crate::attributes::prototype::CustomMirParser;
6060
use crate::attributes::repr::{AlignParser, AlignStaticParser, ReprParser};
6161
use crate::attributes::rustc_internal::{
62-
RustcLayoutScalarValidRangeEndParser, RustcLayoutScalarValidRangeStartParser, RustcMainParser,
63-
RustcObjectLifetimeDefaultParser, RustcSimdMonomorphizeLaneLimitParser,
62+
RustcLayoutScalarValidRangeEndParser, RustcLayoutScalarValidRangeStartParser,
63+
RustcLegacyConstGenericsParser, RustcMainParser, RustcObjectLifetimeDefaultParser,
64+
RustcSimdMonomorphizeLaneLimitParser,
6465
};
6566
use crate::attributes::semantics::MayDangleParser;
6667
use crate::attributes::stability::{
@@ -208,6 +209,7 @@ attribute_parsers!(
208209
Single<RustcForceInlineParser>,
209210
Single<RustcLayoutScalarValidRangeEndParser>,
210211
Single<RustcLayoutScalarValidRangeStartParser>,
212+
Single<RustcLegacyConstGenericsParser>,
211213
Single<RustcObjectLifetimeDefaultParser>,
212214
Single<RustcSimdMonomorphizeLaneLimitParser>,
213215
Single<SanitizeParser>,

compiler/rustc_hir/src/attrs/data_structures.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,9 @@ pub enum AttributeKind {
869869
/// Represents `#[rustc_layout_scalar_valid_range_start]`.
870870
RustcLayoutScalarValidRangeStart(Box<u128>, Span),
871871

872+
/// Represents `#[rustc_legacy_const_generics]`
873+
RustcLegacyConstGenerics { fn_indexes: ThinVec<(usize, Span)>, attr_span: Span },
874+
872875
/// Represents `#[rustc_main]`.
873876
RustcMain,
874877

compiler/rustc_hir/src/attrs/encode_cross_crate.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ impl AttributeKind {
9292
RustcCoherenceIsCore(..) => No,
9393
RustcLayoutScalarValidRangeEnd(..) => Yes,
9494
RustcLayoutScalarValidRangeStart(..) => Yes,
95+
RustcLegacyConstGenerics { .. } => Yes,
9596
RustcMain => No,
9697
RustcObjectLifetimeDefault => No,
9798
RustcPassIndirectlyInNonRusticAbis(..) => No,

compiler/rustc_hir/src/attrs/pretty_printing.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ macro_rules! print_tup {
159159

160160
print_tup!(A B C D E F G H);
161161
print_skip!(Span, (), ErrorGuaranteed);
162-
print_disp!(u16, u128, bool, NonZero<u32>, Limit);
162+
print_disp!(u16, u128, usize, bool, NonZero<u32>, Limit);
163163
print_debug!(
164164
Symbol,
165165
Ident,

compiler/rustc_middle/src/ty/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,6 @@ pub struct ResolverGlobalCtxt {
195195
#[derive(Debug)]
196196
pub struct ResolverAstLowering {
197197
pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
198-
199198
/// Resolutions for nodes that have a single resolution.
200199
pub partial_res_map: NodeMap<hir::def::PartialRes>,
201200
/// Resolutions for import nodes, which have multiple resolutions in different namespaces.

compiler/rustc_passes/messages.ftl

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -478,9 +478,6 @@ passes_rustc_legacy_const_generics_index_exceed =
478478
*[other] arguments
479479
}
480480
481-
passes_rustc_legacy_const_generics_index_negative =
482-
arguments should be non-negative integers
483-
484481
passes_rustc_legacy_const_generics_only =
485482
#[rustc_legacy_const_generics] functions must only have const generics
486483
.label = non-const generic parameter

compiler/rustc_passes/src/check_attr.rs

Lines changed: 19 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ use std::collections::hash_map::Entry;
1010
use std::slice;
1111

1212
use rustc_abi::{Align, ExternAbi, Size};
13-
use rustc_ast::{AttrStyle, LitKind, MetaItemKind, ast};
13+
use rustc_ast::{AttrStyle, MetaItemKind, ast};
1414
use rustc_attr_parsing::{AttributeParser, Late};
1515
use rustc_data_structures::fx::FxHashMap;
16+
use rustc_data_structures::thin_vec::ThinVec;
1617
use rustc_errors::{DiagCtxtHandle, IntoDiagArg, MultiSpan, StashKey};
1718
use rustc_feature::{
1819
ACCEPTED_LANG_FEATURES, AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP,
@@ -211,6 +212,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
211212
Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => {
212213
self.check_macro_export(hir_id, *span, target)
213214
},
215+
Attribute::Parsed(AttributeKind::RustcLegacyConstGenerics{attr_span, fn_indexes}) => {
216+
self.check_rustc_legacy_const_generics(item, *attr_span, fn_indexes)
217+
},
214218
Attribute::Parsed(AttributeKind::Doc(attr)) => self.check_doc_attrs(attr, hir_id, target),
215219
Attribute::Parsed(AttributeKind::EiiImpls(impls)) => {
216220
self.check_eii_impl(impls, target)
@@ -305,9 +309,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
305309
[sym::rustc_never_returns_null_ptr, ..] => {
306310
self.check_applied_to_fn_or_method(hir_id, attr.span(), span, target)
307311
}
308-
[sym::rustc_legacy_const_generics, ..] => {
309-
self.check_rustc_legacy_const_generics(hir_id, attr, span, target, item)
310-
}
311312
[sym::rustc_lint_query_instability, ..] => {
312313
self.check_applied_to_fn_or_method(hir_id, attr.span(), span, target)
313314
}
@@ -1217,76 +1218,49 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
12171218
/// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
12181219
fn check_rustc_legacy_const_generics(
12191220
&self,
1220-
hir_id: HirId,
1221-
attr: &Attribute,
1222-
span: Span,
1223-
target: Target,
12241221
item: Option<ItemLike<'_>>,
1222+
attr_span: Span,
1223+
index_list: &ThinVec<(usize, Span)>,
12251224
) {
1226-
let is_function = matches!(target, Target::Fn);
1227-
if !is_function {
1228-
self.dcx().emit_err(errors::AttrShouldBeAppliedToFn {
1229-
attr_span: attr.span(),
1230-
defn_span: span,
1231-
on_crate: hir_id == CRATE_HIR_ID,
1232-
});
1233-
return;
1234-
}
1235-
1236-
let Some(list) = attr.meta_item_list() else {
1237-
// The attribute form is validated on AST.
1238-
return;
1239-
};
1240-
12411225
let Some(ItemLike::Item(Item {
12421226
kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
12431227
..
12441228
})) = item
12451229
else {
1246-
bug!("should be a function item");
1230+
// No error here, since it's already given by the parser
1231+
return;
12471232
};
12481233

12491234
for param in generics.params {
12501235
match param.kind {
12511236
hir::GenericParamKind::Const { .. } => {}
12521237
_ => {
12531238
self.dcx().emit_err(errors::RustcLegacyConstGenericsOnly {
1254-
attr_span: attr.span(),
1239+
attr_span,
12551240
param_span: param.span,
12561241
});
12571242
return;
12581243
}
12591244
}
12601245
}
12611246

1262-
if list.len() != generics.params.len() {
1247+
if index_list.len() != generics.params.len() {
12631248
self.dcx().emit_err(errors::RustcLegacyConstGenericsIndex {
1264-
attr_span: attr.span(),
1249+
attr_span,
12651250
generics_span: generics.span,
12661251
});
12671252
return;
12681253
}
12691254

1270-
let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1271-
let mut invalid_args = vec![];
1272-
for meta in list {
1273-
if let Some(LitKind::Int(val, _)) = meta.lit().map(|lit| &lit.kind) {
1274-
if *val >= arg_count {
1275-
let span = meta.span();
1276-
self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1277-
span,
1278-
arg_count: arg_count as usize,
1279-
});
1280-
return;
1281-
}
1282-
} else {
1283-
invalid_args.push(meta.span());
1255+
let arg_count = decl.inputs.len() + generics.params.len();
1256+
for (index, span) in index_list {
1257+
if *index >= arg_count {
1258+
self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1259+
span: *span,
1260+
arg_count,
1261+
});
12841262
}
12851263
}
1286-
1287-
if !invalid_args.is_empty() {
1288-
self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1289-
}
12901264
}
12911265

12921266
/// Helper function for checking that the provided attribute is only applied to a function or

compiler/rustc_passes/src/errors.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -290,13 +290,6 @@ pub(crate) struct RustcLegacyConstGenericsIndexExceed {
290290
pub arg_count: usize,
291291
}
292292

293-
#[derive(Diagnostic)]
294-
#[diag(passes_rustc_legacy_const_generics_index_negative)]
295-
pub(crate) struct RustcLegacyConstGenericsIndexNegative {
296-
#[primary_span]
297-
pub invalid_args: Vec<Span>,
298-
}
299-
300293
#[derive(Diagnostic)]
301294
#[diag(passes_rustc_dirty_clean)]
302295
pub(crate) struct RustcDirtyClean {

0 commit comments

Comments
 (0)