1
Fork 0

ast: Optimize list and value extraction primitives for attributes

It's not necessary to convert the whole attribute into a meta item to extract something specific
This commit is contained in:
Vadim Petrochenkov 2023-02-01 20:26:05 +04:00
parent 11d96b5930
commit a9c8a5c025
4 changed files with 90 additions and 76 deletions

View file

@ -1826,6 +1826,13 @@ pub enum LitKind {
} }
impl LitKind { impl LitKind {
pub fn str(&self) -> Option<Symbol> {
match *self {
LitKind::Str(s, _) => Some(s),
_ => None,
}
}
/// Returns `true` if this literal is a string. /// Returns `true` if this literal is a string.
pub fn is_str(&self) -> bool { pub fn is_str(&self) -> bool {
matches!(self, LitKind::Str(..)) matches!(self, LitKind::Str(..))

View file

@ -140,17 +140,14 @@ impl Attribute {
pub fn value_str(&self) -> Option<Symbol> { pub fn value_str(&self) -> Option<Symbol> {
match &self.kind { match &self.kind {
AttrKind::Normal(normal) => normal.item.meta_kind().and_then(|kind| kind.value_str()), AttrKind::Normal(normal) => normal.item.value_str(),
AttrKind::DocComment(..) => None, AttrKind::DocComment(..) => None,
} }
} }
pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> { pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
match &self.kind { match &self.kind {
AttrKind::Normal(normal) => match normal.item.meta_kind() { AttrKind::Normal(normal) => normal.item.meta_item_list(),
Some(MetaItemKind::List(list)) => Some(list),
_ => None,
},
AttrKind::DocComment(..) => None, AttrKind::DocComment(..) => None,
} }
} }
@ -216,6 +213,20 @@ impl MetaItem {
} }
} }
impl AttrArgsEq {
fn value_str(&self) -> Option<Symbol> {
match self {
AttrArgsEq::Ast(expr) => match expr.kind {
ExprKind::Lit(token_lit) => {
LitKind::from_token_lit(token_lit).ok().and_then(|lit| lit.str())
}
_ => None,
},
AttrArgsEq::Hir(lit) => lit.kind.str(),
}
}
}
impl AttrItem { impl AttrItem {
pub fn span(&self) -> Span { pub fn span(&self) -> Span {
self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span)) self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
@ -228,6 +239,22 @@ impl AttrItem {
pub fn meta_kind(&self) -> Option<MetaItemKind> { pub fn meta_kind(&self) -> Option<MetaItemKind> {
MetaItemKind::from_attr_args(&self.args) MetaItemKind::from_attr_args(&self.args)
} }
fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
match &self.args {
AttrArgs::Delimited(args) if args.delim == MacDelimiter::Parenthesis => {
MetaItemKind::list_from_tokens(args.tokens.clone())
}
AttrArgs::Delimited(_) | AttrArgs::Eq(..) | AttrArgs::Empty => None,
}
}
fn value_str(&self) -> Option<Symbol> {
match &self.args {
AttrArgs::Eq(_, args) => args.value_str(),
AttrArgs::Delimited(_) | AttrArgs::Empty => None,
}
}
} }
impl Attribute { impl Attribute {
@ -247,13 +274,11 @@ impl Attribute {
/// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`. /// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`.
/// * `#[doc(...)]` returns `None`. /// * `#[doc(...)]` returns `None`.
pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> { pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
match self.kind { match &self.kind {
AttrKind::DocComment(kind, data) => Some((data, kind)), AttrKind::DocComment(kind, data) => Some((*data, *kind)),
AttrKind::Normal(ref normal) if normal.item.path == sym::doc => normal AttrKind::Normal(normal) if normal.item.path == sym::doc => {
.item normal.item.value_str().map(|s| (s, CommentKind::Line))
.meta_kind() }
.and_then(|kind| kind.value_str())
.map(|data| (data, CommentKind::Line)),
_ => None, _ => None,
} }
} }
@ -265,9 +290,7 @@ impl Attribute {
pub fn doc_str(&self) -> Option<Symbol> { pub fn doc_str(&self) -> Option<Symbol> {
match &self.kind { match &self.kind {
AttrKind::DocComment(.., data) => Some(*data), AttrKind::DocComment(.., data) => Some(*data),
AttrKind::Normal(normal) if normal.item.path == sym::doc => { AttrKind::Normal(normal) if normal.item.path == sym::doc => normal.item.value_str(),
normal.item.meta_kind().and_then(|kind| kind.value_str())
}
_ => None, _ => None,
} }
} }
@ -508,15 +531,12 @@ impl MetaItem {
impl MetaItemKind { impl MetaItemKind {
pub fn value_str(&self) -> Option<Symbol> { pub fn value_str(&self) -> Option<Symbol> {
match self { match self {
MetaItemKind::NameValue(v) => match v.kind { MetaItemKind::NameValue(v) => v.kind.str(),
LitKind::Str(s, _) => Some(s),
_ => None,
},
_ => None, _ => None,
} }
} }
fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> { fn list_from_tokens(tokens: TokenStream) -> Option<Vec<NestedMetaItem>> {
let mut tokens = tokens.into_trees().peekable(); let mut tokens = tokens.into_trees().peekable();
let mut result = Vec::new(); let mut result = Vec::new();
while tokens.peek().is_some() { while tokens.peek().is_some() {
@ -527,7 +547,7 @@ impl MetaItemKind {
_ => return None, _ => return None,
} }
} }
Some(MetaItemKind::List(result)) Some(result)
} }
fn name_value_from_tokens( fn name_value_from_tokens(
@ -551,7 +571,7 @@ impl MetaItemKind {
dspan: _, dspan: _,
delim: MacDelimiter::Parenthesis, delim: MacDelimiter::Parenthesis,
tokens, tokens,
}) => MetaItemKind::list_from_tokens(tokens.clone()), }) => MetaItemKind::list_from_tokens(tokens.clone()).map(MetaItemKind::List),
AttrArgs::Delimited(..) => None, AttrArgs::Delimited(..) => None,
AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => match expr.kind { AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => match expr.kind {
ExprKind::Lit(token_lit) => { ExprKind::Lit(token_lit) => {
@ -573,7 +593,7 @@ impl MetaItemKind {
Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => { Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => {
let inner_tokens = inner_tokens.clone(); let inner_tokens = inner_tokens.clone();
tokens.next(); tokens.next();
MetaItemKind::list_from_tokens(inner_tokens) MetaItemKind::list_from_tokens(inner_tokens).map(MetaItemKind::List)
} }
Some(TokenTree::Delimited(..)) => None, Some(TokenTree::Delimited(..)) => None,
Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => { Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {

View file

@ -319,8 +319,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs {
} }
} }
} else if attr.has_name(sym::instruction_set) { } else if attr.has_name(sym::instruction_set) {
codegen_fn_attrs.instruction_set = match attr.meta_kind() { codegen_fn_attrs.instruction_set = attr.meta_item_list().and_then(|l| match &l[..] {
Some(MetaItemKind::List(ref items)) => match items.as_slice() {
[NestedMetaItem::MetaItem(set)] => { [NestedMetaItem::MetaItem(set)] => {
let segments = let segments =
set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>(); set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
@ -375,18 +374,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs {
.emit(); .emit();
None None
} }
}, })
_ => {
struct_span_err!(
tcx.sess.diagnostic(),
attr.span,
E0778,
"must specify an instruction set"
)
.emit();
None
}
};
} else if attr.has_name(sym::repr) { } else if attr.has_name(sym::repr) {
codegen_fn_attrs.alignment = match attr.meta_item_list() { codegen_fn_attrs.alignment = match attr.meta_item_list() {
Some(items) => match items.as_slice() { Some(items) => match items.as_slice() {

View file

@ -4,7 +4,7 @@
//! but are not declared in one single location (unlike lang features), which means we need to //! but are not declared in one single location (unlike lang features), which means we need to
//! collect them instead. //! collect them instead.
use rustc_ast::{Attribute, MetaItemKind}; use rustc_ast::Attribute;
use rustc_attr::{rust_version_symbol, VERSION_PLACEHOLDER}; use rustc_attr::{rust_version_symbol, VERSION_PLACEHOLDER};
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
@ -42,8 +42,7 @@ impl<'tcx> LibFeatureCollector<'tcx> {
// Find a stability attribute: one of #[stable(…)], #[unstable(…)], // Find a stability attribute: one of #[stable(…)], #[unstable(…)],
// #[rustc_const_stable(…)], #[rustc_const_unstable(…)] or #[rustc_default_body_unstable]. // #[rustc_const_stable(…)], #[rustc_const_unstable(…)] or #[rustc_default_body_unstable].
if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| attr.has_name(**stab_attr)) { if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| attr.has_name(**stab_attr)) {
let meta_kind = attr.meta_kind(); if let Some(metas) = attr.meta_item_list() {
if let Some(MetaItemKind::List(ref metas)) = meta_kind {
let mut feature = None; let mut feature = None;
let mut since = None; let mut since = None;
for meta in metas { for meta in metas {