Skip to content

AttrTarget demo #1

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 2 commits 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, AttrTarget::Todo, l.span);
self.arena.alloc(hir::LetStmt { hir_id, super_, ty, pat, init, els, span, source })
}

Expand Down
16 changes: 9 additions & 7 deletions compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::sync::Arc;
use rustc_ast::ptr::P as AstP;
use rustc_ast::*;
use rustc_ast_pretty::pprust::expr_to_string;
use rustc_attr_parsing::AttrTarget;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir as hir;
use rustc_hir::HirId;
Expand Down Expand Up @@ -74,7 +75,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, AttrTarget::Todo, e.span, ex.hir_id)
.into_iter()
.chain(old_attrs.iter().cloned());
let new_attrs = &*self.arena.alloc_from_iter(new_attrs);
Expand All @@ -97,7 +98,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, AttrTarget::Todo, e.span);

let kind = match &e.kind {
ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
Expand Down Expand Up @@ -677,7 +678,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, AttrTarget::Todo, arm.span);
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 @@ -849,6 +850,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
style: AttrStyle::Outer,
span: unstable_span,
}],
AttrTarget::Todo,
span,
);
}
Expand Down Expand Up @@ -1690,7 +1692,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, AttrTarget::Todo, f.span);
hir::ExprField {
hir_id,
ident: self.lower_ident(f.ident),
Expand Down Expand Up @@ -1946,7 +1948,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, AttrTarget::Todo, e.span);
expr
}

Expand Down Expand Up @@ -2003,7 +2005,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
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, AttrTarget::Todo, span);
let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
self.arm(continue_pat, val_expr)
};
Expand Down Expand Up @@ -2034,7 +2036,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, AttrTarget::Todo, span);

let break_pat = self.pat_cf_break(try_span, residual_local);
self.arm(break_pat, ret_expr)
Expand Down
24 changes: 15 additions & 9 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;
use rustc_errors::ErrorGuaranteed;
use rustc_hir::def::{DefKind, PerNS, Res};
use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
Expand Down Expand Up @@ -82,7 +83,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, AttrTarget::Todo, DUMMY_SP);
hir::OwnerNode::Crate(module)
})
}
Expand Down Expand Up @@ -138,7 +139,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, AttrTarget::from(&i.kind), i.span);
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 @@ -641,7 +642,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, AttrTarget::Todo, i.span);
let (ident, kind) = match &i.kind {
ForeignItemKind::Fn(box Fn { sig, ident, generics, define_opaque, .. }) => {
let fdec = &sig.decl;
Expand Down Expand Up @@ -716,7 +717,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

fn lower_variant(&mut self, 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, AttrTarget::Todo, v.span);
hir::Variant {
hir_id,
def_id: self.local_def_id(v.id),
Expand Down Expand Up @@ -778,7 +779,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, AttrTarget::Todo, f.span);
hir::FieldDef {
span: self.lower_span(f.span),
hir_id,
Expand All @@ -797,7 +798,7 @@ 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 attrs = self.lower_attrs(hir_id, &i.attrs, AttrTarget::from((true, &i.kind)), i.span);
let trait_item_def_id = hir_id.expect_owner();

let (ident, generics, kind, has_default) = match &i.kind {
Expand Down Expand Up @@ -991,7 +992,12 @@ 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 attrs = self.lower_attrs(
hir_id,
&i.attrs,
AttrTarget::from((is_in_trait_impl, &i.kind)),
i.span,
);

let (ident, (generics, kind)) = match &i.kind {
AssocItemKind::Const(box ConstItem {
Expand Down Expand Up @@ -1185,7 +1191,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, AttrTarget::Todo, param.span);
hir::Param {
hir_id,
pat: self.lower_pat(&param.pat),
Expand Down Expand Up @@ -1894,7 +1900,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, AttrTarget::Todo, span);
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 @@ -911,12 +911,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
&mut self,
id: HirId,
attrs: &[Attribute],
target: AttrTarget<'_>,
target_span: Span,
) -> &'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, target, self.lower_span(target_span), id);

assert_eq!(id.owner, self.current_hir_id_owner);
let ret = self.arena.alloc_from_iter(lowered_attrs);
Expand All @@ -939,12 +941,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn lower_attrs_vec(
&mut self,
attrs: &[Attribute],
target: AttrTarget<'_>,
target_span: Span,
target_hir_id: HirId,
) -> Vec<hir::Attribute> {
let l = self.span_lowerer();
self.attribute_parser.parse_attribute_list(
attrs,
target,
target_span,
target_hir_id,
OmitDoc::Lower,
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, AttrTarget::Todo, param.span());
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, AttrTarget::Todo, f.span);

hir::PatField {
hir_id,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/attributes/deprecation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ impl<S: Stage> SingleAttributeParser<S> for DeprecationParser {
const PATH: &[Symbol] = &[sym::deprecated];
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst;
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const POSITIONS: &[crate::TargetChecker] = &[crate::allowed!(_)];

fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
let features = cx.features();
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ impl<S: Stage> SingleAttributeParser<S> for AsPtrParser {
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst;

const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const POSITIONS: &[crate::TargetChecker] = &[crate::allowed!(Function | Method)];

fn convert(cx: &mut AcceptContext<'_, '_, S>, _args: &ArgParser<'_>) -> Option<AttributeKind> {
// FIXME: check that there's no args (this is currently checked elsewhere)
Expand Down
21 changes: 21 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use rustc_attr_data_structures::lints::AttributeLintKind;
use rustc_span::{Span, Symbol};
use thin_vec::ThinVec;

use crate::TargetChecker;
use crate::context::{AcceptContext, FinalizeContext, Stage};
use crate::parser::ArgParser;
use crate::session_diagnostics::UnusedMultiple;
Expand Down Expand Up @@ -87,6 +88,7 @@ pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
const PATH: &[Symbol];
const ATTRIBUTE_ORDER: AttributeOrder;
const ON_DUPLICATE: OnDuplicate<S>;
const POSITIONS: &[TargetChecker];

/// Converts a single syntactical attribute to a single semantic attribute, or [`AttributeKind`]
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind>;
Expand All @@ -106,6 +108,25 @@ impl<T: SingleAttributeParser<S>, S: Stage> Default for Single<T, S> {
impl<T: SingleAttributeParser<S>, S: Stage> AttributeParser<S> for Single<T, S> {
const ATTRIBUTES: AcceptMapping<Self, S> =
&[(T::PATH, |group: &mut Single<T, S>, cx, args| {
let mut allowed = false;
for checker in T::POSITIONS {
for pos in checker.check {
allowed |= pos(cx.target);
}
}

if !allowed {
let allowed_targets = crate::AttrTarget::allowed(T::POSITIONS);
cx.dcx().span_err(
cx.attr_span,
format!(
"`{}` is not valid at that position. It is only allowed in {:?}",
crate::attributes::util::PathPrinter(T::PATH),
allowed_targets,
),
);
return;
}
if let Some(pa) = T::convert(cx, args) {
match T::ATTRIBUTE_ORDER {
// keep the first and report immediately. ignore this attribute
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/stability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use rustc_span::{Span, Symbol, sym};

use super::util::parse_version;
use super::{AcceptMapping, AttributeOrder, AttributeParser, OnDuplicate, SingleAttributeParser};
use crate::allowed;
use crate::context::{AcceptContext, FinalizeContext, Stage};
use crate::parser::{ArgParser, MetaItemParser};
use crate::session_diagnostics::{self, UnsupportedLiteralReason};
Expand Down Expand Up @@ -120,6 +121,7 @@ impl<S: Stage> SingleAttributeParser<S> for ConstStabilityIndirectParser {
const PATH: &[Symbol] = &[sym::rustc_const_stable_indirect];
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst;
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Ignore;
const POSITIONS: &[crate::TargetChecker] = &[allowed!(_)];

fn convert(_cx: &mut AcceptContext<'_, '_, S>, _args: &ArgParser<'_>) -> Option<AttributeKind> {
Some(AttributeKind::ConstStabilityIndirect)
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_attr_parsing/src/attributes/transparency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use rustc_span::hygiene::Transparency;
use rustc_span::{Symbol, sym};

use super::{AttributeOrder, OnDuplicate, SingleAttributeParser};
use crate::allowed;
use crate::context::{AcceptContext, Stage};
use crate::parser::ArgParser;

pub(crate) struct TransparencyParser;

// FIXME(jdonszelmann): make these proper diagnostics
Expand All @@ -17,6 +17,7 @@ impl<S: Stage> SingleAttributeParser<S> for TransparencyParser {
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Custom(|cx, used, unused| {
cx.dcx().span_err(vec![used, unused], "multiple macro transparency attributes");
});
const POSITIONS: &[crate::TargetChecker] = &[allowed!(_)];

fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
match args.name_value().and_then(|nv| nv.value_as_str()) {
Expand Down
24 changes: 24 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/util.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt;

use rustc_ast::attr::{AttributeExt, first_attr_value_str_by_name};
use rustc_attr_data_structures::RustcVersion;
use rustc_feature::is_builtin_attr_name;
Expand Down Expand Up @@ -56,3 +58,25 @@ pub fn is_doc_alias_attrs_contain_symbol<'tcx, T: AttributeExt + 'tcx>(
}
false
}

pub(crate) struct PathPrinter<'s>(pub &'s [Symbol]);

impl fmt::Display for PathPrinter<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#[")?;
match &self.0 {
&[] => {}
&[one] => {
write!(f, "{one}")?;
}
&[start @ .., last] => {
for segment in start {
write!(f, "{segment}::")?;
}
write!(f, "{last}")?;
}
}
write!(f, "]")?;
Ok(())
}
}
Loading