Skip to content

Commit 92bbba6

Browse files
committed
refactor: more general terminology and use existing attr parse machinery
1 parent 4f6c6c5 commit 92bbba6

File tree

10 files changed

+119
-120
lines changed

10 files changed

+119
-120
lines changed

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -653,13 +653,29 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
653653
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();
654654

655655
for def_id in ast_index.indices() {
656-
match &ast_index[def_id] {
657-
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
658-
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
659-
delayed_ids.insert(def_id);
656+
let delayed_owner_kind = match &ast_index[def_id] {
657+
AstOwner::Item(Item { kind: ItemKind::Delegation(..), .. }) => {
658+
Some(hir::DelayedOwnerKind::Item)
660659
}
661-
_ => lowerer.lower_node(def_id),
660+
AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(..), .. }, ctx) => {
661+
Some(match ctx {
662+
visit::AssocCtxt::Trait => hir::DelayedOwnerKind::TraitItem,
663+
visit::AssocCtxt::Impl { .. } => hir::DelayedOwnerKind::ImplItem,
664+
})
665+
}
666+
_ => None,
662667
};
668+
669+
if let Some(kind) = delayed_owner_kind {
670+
delayed_ids.insert(def_id);
671+
672+
let owner = lowerer.owners.get_or_insert_mut(def_id);
673+
if let hir::MaybeOwner::Phantom = owner {
674+
*owner = hir::MaybeOwner::Delayed(kind)
675+
}
676+
} else {
677+
lowerer.lower_node(def_id);
678+
}
663679
}
664680

665681
// Don't hash unless necessary, because it's expensive.

compiler/rustc_attr_parsing/src/attributes/repr.rs

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use rustc_abi::{Align, Size};
22
use rustc_ast::{IntTy, LitIntType, LitKind, UintTy};
3-
use rustc_hir::attrs::{AttrConstResolved, AttrIntValue, IntType, ReprAttr};
3+
use rustc_hir::attrs::{AttrIntValue, AttrResolutionKind, AttrResolved, IntType, ReprAttr};
44
use rustc_hir::def::{DefKind, Res};
55
use rustc_session::parse::feature_err;
66

@@ -105,7 +105,10 @@ fn int_type_of_word(s: Symbol) -> Option<IntType> {
105105
}
106106
}
107107

108-
fn parse_repr<S: Stage>(cx: &AcceptContext<'_, '_, S>, param: &MetaItemParser) -> Option<ReprAttr> {
108+
fn parse_repr<S: Stage>(
109+
cx: &mut AcceptContext<'_, '_, S>,
110+
param: &MetaItemParser,
111+
) -> Option<ReprAttr> {
109112
use ReprAttr::*;
110113

111114
// FIXME(jdonszelmann): invert the parsing here to match on the word first and then the
@@ -200,7 +203,7 @@ enum AlignmentParseError {
200203
}
201204

202205
fn parse_repr_align<S: Stage>(
203-
cx: &AcceptContext<'_, '_, S>,
206+
cx: &mut AcceptContext<'_, '_, S>,
204207
list: &MetaItemListParser,
205208
param_span: Span,
206209
align_kind: AlignKind,
@@ -283,7 +286,7 @@ fn parse_alignment<S: Stage>(
283286
}
284287

285288
fn parse_alignment_or_const_path<S: Stage>(
286-
cx: &AcceptContext<'_, '_, S>,
289+
cx: &mut AcceptContext<'_, '_, S>,
287290
arg: &MetaItemOrLitParser,
288291
attr_name: &'static str,
289292
) -> Result<AttrIntValue, AlignmentParseError> {
@@ -301,10 +304,15 @@ fn parse_alignment_or_const_path<S: Stage>(
301304
return Err(AlignmentParseError::Message("not an unsuffixed integer".to_string()));
302305
}
303306

304-
if let Some(features) = cx.features_option()
305-
&& !features.const_attr_paths()
306-
&& !meta.span().allows_unstable(sym::const_attr_paths)
307-
{
307+
let path_span = meta.path().span();
308+
let feature_enabled = cx.features_option().is_some_and(|features| features.const_attr_paths())
309+
|| path_span.allows_unstable(sym::const_attr_paths);
310+
311+
if !feature_enabled {
312+
if matches!(cx.stage.should_emit(), ShouldEmit::Nothing) {
313+
return Ok(AttrIntValue::Lit(1));
314+
}
315+
308316
feature_err(
309317
cx.sess(),
310318
sym::const_attr_paths,
@@ -315,7 +323,9 @@ fn parse_alignment_or_const_path<S: Stage>(
315323
return Err(AlignmentParseError::AlreadyErrored);
316324
}
317325

318-
let Some(resolution) = cx.attr_const_resolution(meta.path().span()) else {
326+
cx.record_attr_resolution_request(AttrResolutionKind::Const, meta.path().0.clone());
327+
328+
let Some(resolution) = cx.attr_resolution(AttrResolutionKind::Const, path_span) else {
319329
// `parse_limited(sym::repr)` runs before lowering for callers that only care whether
320330
// `repr(packed(...))` exists at all.
321331
if matches!(cx.stage.should_emit(), ShouldEmit::Nothing) {
@@ -325,22 +335,18 @@ fn parse_alignment_or_const_path<S: Stage>(
325335
};
326336

327337
match resolution {
328-
AttrConstResolved::Resolved(Res::Def(DefKind::Const { .. }, def_id)) => {
329-
Ok(AttrIntValue::Const { def_id, span: meta.path().span() })
338+
AttrResolved::Resolved(Res::Def(DefKind::Const { .. }, def_id)) => {
339+
Ok(AttrIntValue::Const { def_id, span: path_span })
330340
}
331-
AttrConstResolved::Resolved(Res::Def(DefKind::ConstParam, _)) => {
332-
cx.emit_err(AttrConstGenericNotSupported { span: meta.path().span(), attr_name });
341+
AttrResolved::Resolved(Res::Def(DefKind::ConstParam, _)) => {
342+
cx.emit_err(AttrConstGenericNotSupported { span: path_span, attr_name });
333343
Err(AlignmentParseError::AlreadyErrored)
334344
}
335-
AttrConstResolved::Resolved(res) => {
336-
cx.emit_err(AttrConstPathNotConst {
337-
span: meta.path().span(),
338-
attr_name,
339-
thing: res.descr(),
340-
});
345+
AttrResolved::Resolved(res) => {
346+
cx.emit_err(AttrConstPathNotConst { span: path_span, attr_name, thing: res.descr() });
341347
Err(AlignmentParseError::AlreadyErrored)
342348
}
343-
AttrConstResolved::Error => Err(AlignmentParseError::AlreadyErrored),
349+
AttrResolved::Error => Err(AlignmentParseError::AlreadyErrored),
344350
}
345351
}
346352

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ use crate::attributes::dummy::*;
3737
use crate::attributes::inline::*;
3838
use crate::attributes::instruction_set::*;
3939
use crate::attributes::link_attrs::*;
40-
use crate::attributes::lint::*;
4140
use crate::attributes::lint_helpers::*;
4241
use crate::attributes::loop_match::*;
4342
use crate::attributes::macro_attrs::*;
@@ -150,7 +149,6 @@ attribute_parsers!(
150149
ConfusablesParser,
151150
ConstStabilityParser,
152151
DocParser,
153-
LintParser,
154152
MacroUseParser,
155153
NakedParser,
156154
OnConstParser,
@@ -827,17 +825,6 @@ where
827825
)
828826
}
829827

830-
pub(crate) fn expected_nv_as_last_argument(
831-
&mut self,
832-
span: Span,
833-
name_value_key: Symbol,
834-
) -> ErrorGuaranteed {
835-
self.emit_parse_error(
836-
span,
837-
AttributeParseErrorReason::ExpectedNameValueAsLastArgument { span, name_value_key },
838-
)
839-
}
840-
841828
pub(crate) fn warn_empty_attribute(&mut self, span: Span) {
842829
let attr_path = self.attr_path.clone().to_string();
843830
let valid_without_list = self.template.word;

compiler/rustc_attr_parsing/src/interface.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -577,9 +577,11 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
577577

578578
let attr = Attribute::Unparsed(Box::new(attr));
579579

580-
if self
581-
.tools
582-
.is_some_and(|tools| tools.iter().any(|tool| tool.name == parts[0]))
580+
if self.tools.iter().any(|tool| *tool == parts[0])
581+
// FIXME: this can be removed once #152369 has been merged.
582+
// https://github.com/rust-lang/rust/pull/152369
583+
|| [sym::allow, sym::deny, sym::expect, sym::forbid, sym::warn]
584+
.contains(&parts[0])
583585
{
584586
attributes.push(attr);
585587
} else {

compiler/rustc_attr_parsing/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,5 +112,5 @@ pub use attributes::cfg::{
112112
pub use attributes::cfg_select::*;
113113
pub use attributes::util::{is_builtin_attr, parse_version};
114114
pub use context::{Early, Late, OmitDoc, ShouldEmit};
115-
pub use interface::AttributeParser;
115+
pub use interface::{AttrResolutionRequest, AttributeParser};
116116
pub use session_diagnostics::ParsedDescription;

compiler/rustc_hir/src/attrs/data_structures.rs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,16 +182,35 @@ pub enum AttrIntValue {
182182
Const { def_id: DefId, span: Span },
183183
}
184184

185+
/// The resolution strategy a parsed builtin attribute argument expects.
186+
#[derive(
187+
Copy,
188+
Clone,
189+
Debug,
190+
PartialEq,
191+
Eq,
192+
HashStable_Generic,
193+
Encodable,
194+
Decodable,
195+
PrintAttribute
196+
)]
197+
pub enum AttrResolutionKind {
198+
Const,
199+
}
200+
201+
/// A resolved attribute argument path, or an error placeholder if resolution failed.
185202
#[derive(Debug, Copy, Clone, HashStable_Generic, Encodable, Decodable, PrintAttribute)]
186-
pub enum AttrConstResolved<Id = ast::NodeId> {
203+
pub enum AttrResolved<Id = ast::NodeId> {
187204
Resolved(Res<Id>),
188205
Error,
189206
}
190207

208+
/// A resolved attribute argument path produced by late resolution for a builtin attribute.
191209
#[derive(Debug, Copy, Clone, HashStable_Generic, Encodable, Decodable, PrintAttribute)]
192-
pub struct AttrConstResolution<Id = ast::NodeId> {
210+
pub struct AttrResolution<Id = ast::NodeId> {
211+
pub kind: AttrResolutionKind,
193212
pub path_span: Span,
194-
pub resolved: AttrConstResolved<Id>,
213+
pub resolved: AttrResolved<Id>,
195214
}
196215

197216
pub enum TransparencyError {

compiler/rustc_hir/src/attrs/pretty_printing.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use rustc_target::spec::SanitizerSet;
1818
use thin_vec::ThinVec;
1919

2020
use crate::HashIgnoredAttrId;
21-
use crate::attrs::{AttrIntValue, LintInstance};
21+
use crate::attrs::AttrIntValue;
2222
use crate::limit::Limit;
2323

2424
/// This trait is used to print attributes in `rustc_hir_pretty`.
@@ -207,7 +207,7 @@ macro_rules! print_tup {
207207

208208
print_tup!(A B C D E F G H);
209209
print_skip!(Span, (), ErrorGuaranteed, AttrId, HashIgnoredAttrId);
210-
print_disp!(u8, u16, u32, u128, usize, bool, NonZero<u32>, Limit, LintInstance);
210+
print_disp!(u8, u16, u32, u128, usize, bool, NonZero<u32>, Limit);
211211
print_debug!(
212212
Symbol,
213213
Ident,

compiler/rustc_middle/src/ty/mod.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use rustc_data_structures::steal::Steal;
3737
use rustc_data_structures::unord::{UnordMap, UnordSet};
3838
use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
3939
use rustc_hir as hir;
40-
use rustc_hir::attrs::{AttrConstResolution, StrippedCfgItem};
40+
use rustc_hir::attrs::{AttrResolution, StrippedCfgItem};
4141
use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
4242
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
4343
use rustc_hir::{LangItem, attrs as attr, find_attr};
@@ -210,8 +210,9 @@ pub struct ResolverAstLowering<'tcx> {
210210
pub lifetimes_res_map: NodeMap<LifetimeRes>,
211211
/// Lifetime parameters that lowering will have to introduce.
212212
pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
213-
/// Resolutions for const item paths used in opted-in late attributes, keyed by attribute ID.
214-
pub attr_const_res_map: FxIndexMap<AttrId, Vec<AttrConstResolution<ast::NodeId>>>,
213+
/// Resolutions for builtin attribute arguments that need late name resolution, keyed by
214+
/// attribute ID.
215+
pub attr_res_map: FxIndexMap<AttrId, Vec<AttrResolution<ast::NodeId>>>,
215216

216217
pub next_node_id: ast::NodeId,
217218

0 commit comments

Comments
 (0)