Skip to content

Create AttrTarget for attribute parsing #143284

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion compiler/rustc_ast_lowering/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use rustc_ast::{Block, BlockCheckMode, Local, LocalKind, Stmt, StmtKind};
use rustc_attr_parsing::AttrTarget;
use rustc_hir as hir;
use rustc_span::sym;
use smallvec::SmallVec;
Expand Down Expand Up @@ -109,7 +110,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
};
let span = self.lower_span(l.span);
let source = hir::LocalSource::Normal;
self.lower_attrs(hir_id, &l.attrs, l.span);
self.lower_attrs(hir_id, &l.attrs, l.span, AttrTarget::Let);
self.arena.alloc(hir::LetStmt { hir_id, super_, ty, pat, init, els, span, source })
}

Expand Down
31 changes: 19 additions & 12 deletions compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use rustc_ast::ptr::P as AstP;
use rustc_ast::*;
use rustc_ast_pretty::pprust::expr_to_string;
use rustc_attr_data_structures::{AttributeKind, find_attr};
use rustc_attr_parsing::AttrTarget;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir as hir;
use rustc_hir::HirId;
Expand All @@ -14,7 +15,7 @@ use rustc_middle::ty::TyCtxt;
use rustc_session::errors::report_lit_error;
use rustc_span::source_map::{Spanned, respan};
use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, sym};
use thin_vec::{ThinVec, thin_vec};
use thin_vec::ThinVec;
use visit::{Visitor, walk_expr};

use super::errors::{
Expand Down Expand Up @@ -75,7 +76,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
if !e.attrs.is_empty() {
let old_attrs = self.attrs.get(&ex.hir_id.local_id).copied().unwrap_or(&[]);
let new_attrs = self
.lower_attrs_vec(&e.attrs, e.span, ex.hir_id)
.lower_attrs_vec(&e.attrs, e.span, ex.hir_id, AttrTarget::from_expr(e))
.into_iter()
.chain(old_attrs.iter().cloned());
let new_attrs = &*self.arena.alloc_from_iter(new_attrs);
Expand All @@ -98,7 +99,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
}

let expr_hir_id = self.lower_node_id(e.id);
self.lower_attrs(expr_hir_id, &e.attrs, e.span);
self.lower_attrs(expr_hir_id, &e.attrs, e.span, AttrTarget::from_expr(e));

let kind = match &e.kind {
ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
Expand Down Expand Up @@ -674,7 +675,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let guard = arm.guard.as_ref().map(|cond| self.lower_expr(cond));
let hir_id = self.next_id();
let span = self.lower_span(arm.span);
self.lower_attrs(hir_id, &arm.attrs, arm.span);
self.lower_attrs(hir_id, &arm.attrs, arm.span, AttrTarget::Arm);
let is_never_pattern = pat.is_never_pattern();
// We need to lower the body even if it's unneeded for never pattern in match,
// ensure that we can get HirId for DefId if need (issue #137708).
Expand Down Expand Up @@ -825,6 +826,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
span: Span,
outer_hir_id: HirId,
inner_hir_id: HirId,
target: AttrTarget<'_>,
) {
if self.tcx.features().async_fn_track_caller()
&& let Some(attrs) = self.attrs.get(&outer_hir_id.local_id)
Expand All @@ -847,6 +849,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
span: unstable_span,
}],
span,
target,
);
}
}
Expand Down Expand Up @@ -1218,7 +1221,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
hir::CoroutineSource::Closure,
);

this.maybe_forward_track_caller(body.span, closure_hir_id, expr.hir_id);
this.maybe_forward_track_caller(
body.span,
closure_hir_id,
expr.hir_id,
AttrTarget::from_expr(body),
);

(parameters, expr)
});
Expand Down Expand Up @@ -1687,7 +1695,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
let hir_id = self.lower_node_id(f.id);
self.lower_attrs(hir_id, &f.attrs, f.span);
self.lower_attrs(hir_id, &f.attrs, f.span, AttrTarget::ExprField);
hir::ExprField {
hir_id,
ident: self.lower_ident(f.ident),
Expand Down Expand Up @@ -1943,7 +1951,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
//
// Also, add the attributes to the outer returned expr node.
let expr = self.expr_drop_temps_mut(for_span, match_expr);
self.lower_attrs(expr.hir_id, &e.attrs, e.span);
self.lower_attrs(expr.hir_id, &e.attrs, e.span, AttrTarget::from_expr(e));
expr
}

Expand Down Expand Up @@ -1985,22 +1993,21 @@ impl<'hir> LoweringContext<'_, 'hir> {
};

// `#[allow(unreachable_code)]`
let attr = attr::mk_attr_nested_word(
let attrs = &[attr::mk_attr_nested_word(
&self.tcx.sess.psess.attr_id_generator,
AttrStyle::Outer,
Safety::Default,
sym::allow,
sym::unreachable_code,
try_span,
);
let attrs: AttrVec = thin_vec![attr];
)];

// `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
let continue_arm = {
let val_ident = Ident::with_dummy_span(sym::val);
let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
let val_expr = self.expr_ident(span, val_ident, val_pat_nid);
self.lower_attrs(val_expr.hir_id, &attrs, span);
self.lower_attrs(val_expr.hir_id, attrs, span, AttrTarget::Expression { kind: None });
let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
self.arm(continue_pat, val_expr)
};
Expand Down Expand Up @@ -2031,7 +2038,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let ret_expr = self.checked_return(Some(from_residual_expr));
self.arena.alloc(self.expr(try_span, ret_expr))
};
self.lower_attrs(ret_expr.hir_id, &attrs, span);
self.lower_attrs(ret_expr.hir_id, attrs, span, AttrTarget::Expression { kind: None });

let break_pat = self.pat_cf_break(try_span, residual_local);
self.arm(break_pat, ret_expr)
Expand Down
32 changes: 22 additions & 10 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use rustc_abi::ExternAbi;
use rustc_ast::ptr::P;
use rustc_ast::visit::AssocCtxt;
use rustc_ast::*;
use rustc_attr_parsing::{AttrTarget, Position};
use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err};
use rustc_hir::def::{DefKind, PerNS, Res};
use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
Expand Down Expand Up @@ -83,7 +84,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> {
self.with_lctx(CRATE_NODE_ID, |lctx| {
let module = lctx.lower_mod(&c.items, &c.spans);
// FIXME(jdonszelman): is dummy span ever a problem here?
lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, DUMMY_SP);
lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, DUMMY_SP, AttrTarget::Crate);
hir::OwnerNode::Crate(module)
})
}
Expand Down Expand Up @@ -139,7 +140,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
let vis_span = self.lower_span(i.vis.span);
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span);
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span, AttrTarget::from_item(&i.kind));
let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
let item = hir::Item {
owner_id: hir_id.expect_owner(),
Expand Down Expand Up @@ -229,6 +230,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
body.as_deref(),
attrs,
contract.as_deref(),
AttrTarget::from_item(i),
);

let itctx = ImplTraitContext::Universal;
Expand Down Expand Up @@ -642,7 +644,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let owner_id = hir_id.expect_owner();
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span);
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span, AttrTarget::from_foreign(i));
let (ident, kind) = match &i.kind {
ForeignItemKind::Fn(box Fn { sig, ident, generics, define_opaque, .. }) => {
let fdec = &sig.decl;
Expand Down Expand Up @@ -717,7 +719,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> {
let hir_id = self.lower_node_id(v.id);
self.lower_attrs(hir_id, &v.attrs, v.span);
self.lower_attrs(hir_id, &v.attrs, v.span, AttrTarget::EnumVariant);
hir::Variant {
hir_id,
def_id: self.local_def_id(v.id),
Expand Down Expand Up @@ -800,7 +802,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
) -> hir::FieldDef<'hir> {
let ty = self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy));
let hir_id = self.lower_node_id(f.id);
self.lower_attrs(hir_id, &f.attrs, f.span);
self.lower_attrs(hir_id, &f.attrs, f.span, AttrTarget::Field);
hir::FieldDef {
span: self.lower_span(f.span),
hir_id,
Expand All @@ -819,7 +821,8 @@ impl<'hir> LoweringContext<'_, 'hir> {

fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span);
let target = AttrTarget::from_trait_item(i);
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span, target);
let trait_item_def_id = hir_id.expect_owner();

let (ident, generics, kind, has_default) = match &i.kind {
Expand Down Expand Up @@ -902,6 +905,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
Some(body),
attrs,
contract.as_deref(),
target,
);
let (generics, sig) = self.lower_method_sig(
generics,
Expand Down Expand Up @@ -1013,7 +1017,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
let has_value = true;
let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span);

let target = AttrTarget::from_impl_item(
if is_in_trait_impl { Position::TraitImpl } else { Position::Impl },
i,
);

let attrs = self.lower_attrs(hir_id, &i.attrs, i.span, target);

let (ident, (generics, kind)) = match &i.kind {
AssocItemKind::Const(box ConstItem {
Expand Down Expand Up @@ -1056,6 +1066,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
body.as_deref(),
attrs,
contract.as_deref(),
target,
);
let (generics, sig) = self.lower_method_sig(
generics,
Expand Down Expand Up @@ -1207,7 +1218,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
let hir_id = self.lower_node_id(param.id);
self.lower_attrs(hir_id, &param.attrs, param.span);
self.lower_attrs(hir_id, &param.attrs, param.span, AttrTarget::Param);
hir::Param {
hir_id,
pat: self.lower_pat(&param.pat),
Expand Down Expand Up @@ -1335,6 +1346,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
body: Option<&Block>,
attrs: &'hir [hir::Attribute],
contract: Option<&FnContract>,
target: AttrTarget<'_>,
) -> hir::BodyId {
let Some(body) = body else {
// Functions without a body are an error, except if this is an intrinsic. For those we
Expand Down Expand Up @@ -1382,7 +1394,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

// FIXME(async_fn_track_caller): Can this be moved above?
let hir_id = expr.hir_id;
this.maybe_forward_track_caller(body.span, fn_id, hir_id);
this.maybe_forward_track_caller(body.span, fn_id, hir_id, target);

(parameters, expr)
})
Expand Down Expand Up @@ -1936,7 +1948,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
let hir_id = self.lower_node_id(pred.id);
let span = self.lower_span(pred.span);
self.lower_attrs(hir_id, &pred.attrs, span);
self.lower_attrs(hir_id, &pred.attrs, span, AttrTarget::WherePredicate);
let kind = self.arena.alloc(match &pred.kind {
WherePredicateKind::BoundPredicate(WhereBoundPredicate {
bound_generic_params,
Expand Down
10 changes: 7 additions & 3 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use std::sync::Arc;

use rustc_ast::node_id::NodeMap;
use rustc_ast::{self as ast, *};
use rustc_attr_parsing::{AttributeParser, OmitDoc};
use rustc_attr_parsing::{AttrTarget, AttributeParser, OmitDoc};
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::sorted_map::SortedMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
Expand Down Expand Up @@ -912,11 +912,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
id: HirId,
attrs: &[Attribute],
target_span: Span,
target: AttrTarget<'_>,
) -> &'hir [hir::Attribute] {
if attrs.is_empty() {
&[]
} else {
let lowered_attrs = self.lower_attrs_vec(attrs, self.lower_span(target_span), id);
let lowered_attrs =
self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);

assert_eq!(id.owner, self.current_hir_id_owner);
let ret = self.arena.alloc_from_iter(lowered_attrs);
Expand All @@ -941,12 +943,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
attrs: &[Attribute],
target_span: Span,
target_hir_id: HirId,
target: AttrTarget<'_>,
) -> Vec<hir::Attribute> {
let l = self.span_lowerer();
self.attribute_parser.parse_attribute_list(
attrs,
target_span,
target_hir_id,
target,
OmitDoc::Lower,
|s| l.lower(s),
|l| {
Expand Down Expand Up @@ -1899,7 +1903,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let (name, kind) = self.lower_generic_param_kind(param, source);

let hir_id = self.lower_node_id(param.id);
self.lower_attrs(hir_id, &param.attrs, param.span());
self.lower_attrs(hir_id, &param.attrs, param.span(), AttrTarget::from_generic(param));
hir::GenericParam {
hir_id,
def_id: self.local_def_id(param.id),
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_ast_lowering/src/pat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::sync::Arc;

use rustc_ast::ptr::P;
use rustc_ast::*;
use rustc_attr_parsing::AttrTarget;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{self as hir, LangItem};
Expand Down Expand Up @@ -94,7 +95,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {

let fs = self.arena.alloc_from_iter(fields.iter().map(|f| {
let hir_id = self.lower_node_id(f.id);
self.lower_attrs(hir_id, &f.attrs, f.span);
self.lower_attrs(hir_id, &f.attrs, f.span, AttrTarget::PatField);

hir::PatField {
hir_id,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_attr_data_structures/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ pub enum AttributeKind {
RustcLayoutScalarValidRangeStart(Box<u128>, Span),

/// Represents `#[rustc_skip_during_method_dispatch]`.
SkipDuringMethodDispatch { array: bool, boxed_slice: bool, span: Span },
SkipDuringMethodDispatch { array: bool, boxed_slice: bool },

/// Represents `#[stable]`, `#[unstable]` and `#[rustc_allowed_through_unstable_modules]`.
Stability {
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_attr_parsing/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ attr_parsing_rustc_allowed_unstable_pairing =
attr_parsing_rustc_promotable_pairing =
`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` or a `rustc_const_stable` attribute

attr_parsing_should_be_applied_to_trait =
attribute should be applied to a trait
.label = not a trait

attr_parsing_soft_no_args =
`soft` should not have any arguments

Expand Down
12 changes: 11 additions & 1 deletion compiler/rustc_attr_parsing/src/attributes/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ use rustc_attr_data_structures::AttributeKind;
use rustc_feature::{AttributeTemplate, template};
use rustc_span::{Symbol, sym};

use crate::AttrTarget;
use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser};
use crate::context::{AcceptContext, Stage};
use crate::parser::ArgParser;
use crate::session_diagnostics::AttrShouldBeAppliedToTrait;

pub(crate) struct SkipDuringMethodDispatchParser;

Expand All @@ -18,6 +20,14 @@ impl<S: Stage> SingleAttributeParser<S> for SkipDuringMethodDispatchParser {
const TEMPLATE: AttributeTemplate = template!(List: "array, boxed_slice");

fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
if !matches!(cx.target, AttrTarget::Trait { .. }) {
cx.dcx().emit_err(AttrShouldBeAppliedToTrait {
attr_span: cx.attr_span,
defn_span: cx.target_span,
});
return None;
}

let mut array = false;
let mut boxed_slice = false;
let Some(args) = args.list() else {
Expand Down Expand Up @@ -49,6 +59,6 @@ impl<S: Stage> SingleAttributeParser<S> for SkipDuringMethodDispatchParser {
cx.duplicate_key(arg.span(), key);
}
}
Some(AttributeKind::SkipDuringMethodDispatch { array, boxed_slice, span: cx.attr_span })
Some(AttributeKind::SkipDuringMethodDispatch { array, boxed_slice })
}
}
Loading
Loading