Skip to content

Commit 2d245a4

Browse files
Edvin BryntessonBryntet
authored andcommitted
Port #[rustc_legacy_const_generics] to use attribute parser
Signed-off-by: Edvin Bryntesson <edvin@brynte.me>
1 parent 0208ee0 commit 2d245a4

File tree

15 files changed

+236
-196
lines changed

15 files changed

+236
-196
lines changed

compiler/rustc_ast_lowering/src/expr.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
114114
}
115115
ExprKind::Tup(elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
116116
ExprKind::Call(f, args) => {
117-
if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
117+
if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f, self.tcx)
118+
{
118119
self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
119120
} else {
120121
let f = self.lower_expr(f);

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,14 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
4747
use rustc_data_structures::sync::spawn;
4848
use rustc_data_structures::tagged_ptr::TaggedRef;
4949
use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle};
50+
use rustc_hir::attrs::AttributeKind;
5051
use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
5152
use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId};
5253
use rustc_hir::definitions::{DefPathData, DisambiguatorState};
5354
use rustc_hir::lints::DelayedLint;
5455
use rustc_hir::{
5556
self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
56-
LifetimeSyntax, ParamName, Target, TraitCandidate,
57+
LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr,
5758
};
5859
use rustc_index::{Idx, IndexSlice, IndexVec};
5960
use rustc_macros::extension;
@@ -236,29 +237,30 @@ impl SpanLowerer {
236237

237238
#[extension(trait ResolverAstLoweringExt)]
238239
impl ResolverAstLowering {
239-
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-
}
246-
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-
}
240+
fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'_>) -> Option<Vec<usize>> {
241+
let ExprKind::Path(None, path) = &expr.kind else {
242+
return None;
243+
};
254244

255-
if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
256-
return v.clone();
257-
}
258-
}
245+
// Don't perform legacy const generics rewriting if the path already
246+
// has generic arguments.
247+
if path.segments.last().unwrap().args.is_some() {
248+
return None;
259249
}
260250

261-
None
251+
let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
252+
253+
// We only support cross-crate argument rewriting. Uses
254+
// within the same crate should be updated to use the new
255+
// const generics style.
256+
if def_id.is_local() {
257+
return None;
258+
}
259+
find_attr!(
260+
tcx.get_all_attrs(def_id),
261+
AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
262+
)
263+
.map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
262264
}
263265

264266
fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {

compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs

Lines changed: 53 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,54 @@ 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 meta_items = match args {
93+
ArgParser::List(meta_items) => meta_items,
94+
ArgParser::NoArgs => {
95+
cx.expected_at_least_one_argument(cx.attr_span);
96+
return None;
97+
}
98+
ArgParser::NameValue(_) => {
99+
cx.expected_list(args.span()?);
100+
return None;
101+
}
102+
};
103+
104+
let mut parsed_indexes = ThinVec::new();
105+
let mut errored = false;
106+
107+
for possible_index in meta_items.mixed() {
108+
if let MetaItemOrLitParser::Lit(MetaItemLit {
109+
kind: LitKind::Int(index, LitIntType::Unsuffixed),
110+
..
111+
}) = possible_index
112+
{
113+
parsed_indexes.push((index.0 as usize, possible_index.span()));
114+
} else {
115+
cx.expected_integer_literal(possible_index.span());
116+
errored = true;
117+
}
118+
}
119+
if errored {
120+
return None;
121+
} else if parsed_indexes.is_empty() {
122+
cx.expected_at_least_one_argument(args.span()?);
123+
return None;
124+
}
125+
126+
Some(AttributeKind::RustcLegacyConstGenerics {
127+
fn_indexes: parsed_indexes,
128+
attr_span: cx.attr_span,
129+
})
130+
}
131+
}

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: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use rustc_ast::AttrVec;
2929
use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
3030
use rustc_ast::node_id::NodeMap;
3131
pub use rustc_ast_ir::{Movability, Mutability, try_visit};
32-
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
32+
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
3333
use rustc_data_structures::intern::Interned;
3434
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
3535
use rustc_data_structures::steal::Steal;
@@ -194,8 +194,6 @@ pub struct ResolverGlobalCtxt {
194194
/// This struct is meant to be consumed by lowering.
195195
#[derive(Debug)]
196196
pub struct ResolverAstLowering {
197-
pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
198-
199197
/// Resolutions for nodes that have a single resolution.
200198
pub partial_res_map: NodeMap<hir::def::PartialRes>,
201199
/// 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

0 commit comments

Comments
 (0)