rust/compiler/rustc_ast/src/attr/mod.rs

690 lines
22 KiB
Rust
Raw Normal View History

//! Functions dealing with attributes and meta items.
2019-02-07 02:33:01 +09:00
use crate::ast;
2020-01-11 09:59:14 +01:00
use crate::ast::{AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute};
2019-12-22 17:42:04 -05:00
use crate::ast::{Expr, GenericParam, Item, Lit, LitKind, Local, Stmt, StmtKind};
use crate::ast::{MacArgs, MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem};
2020-04-19 13:00:18 +02:00
use crate::ast::{Path, PathSegment};
2019-02-07 02:33:01 +09:00
use crate::mut_visit::visit_clobber;
use crate::ptr::P;
use crate::token::{self, CommentKind, Token};
2020-11-05 20:27:48 +03:00
use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree, TreeAndSpacing};
2019-02-07 02:33:01 +09:00
2020-01-11 09:59:14 +01:00
use rustc_index::bit_set::GrowableBitSet;
use rustc_span::source_map::{BytePos, Spanned};
2020-04-19 13:00:18 +02:00
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::Span;
use std::iter;
pub struct MarkedAttrs(GrowableBitSet<AttrId>);
2020-01-11 09:59:14 +01:00
impl MarkedAttrs {
// We have no idea how many attributes there will be, so just
// initiate the vectors with 0 bits. We'll grow them as necessary.
pub fn new() -> Self {
MarkedAttrs(GrowableBitSet::new_empty())
2020-01-11 09:59:14 +01:00
}
pub fn mark(&mut self, attr: &Attribute) {
self.0.insert(attr.id);
}
pub fn is_marked(&self, attr: &Attribute) -> bool {
self.0.contains(attr.id)
}
}
pub fn is_known_lint_tool(m_item: Ident) -> bool {
2019-06-24 18:14:04 +02:00
[sym::clippy, sym::rustc].contains(&m_item.name)
2018-07-03 13:50:48 +02:00
}
impl NestedMetaItem {
/// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
pub fn meta_item(&self) -> Option<&MetaItem> {
match *self {
NestedMetaItem::MetaItem(ref item) => Some(item),
2019-12-22 17:42:04 -05:00
_ => None,
}
}
/// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
pub fn literal(&self) -> Option<&Lit> {
match *self {
NestedMetaItem::Literal(ref lit) => Some(lit),
2019-12-22 17:42:04 -05:00
_ => None,
}
}
2019-02-08 14:53:55 +01:00
/// Returns `true` if this list item is a MetaItem with a name of `name`.
pub fn has_name(&self, name: Symbol) -> bool {
self.meta_item().map_or(false, |meta_item| meta_item.has_name(name))
}
/// For a single-segment meta item, returns its name; otherwise, returns `None`.
pub fn ident(&self) -> Option<Ident> {
self.meta_item().and_then(|meta_item| meta_item.ident())
}
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or_else(Ident::invalid).name
}
/// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
/// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
pub fn value_str(&self) -> Option<Symbol> {
self.meta_item().and_then(|meta_item| meta_item.value_str())
}
/// Returns a name and single literal value tuple of the `MetaItem`.
2020-04-19 13:00:18 +02:00
pub fn name_value_literal(&self) -> Option<(Symbol, &Lit)> {
2019-12-22 17:42:04 -05:00
self.meta_item().and_then(|meta_item| {
meta_item.meta_item_list().and_then(|meta_item_list| {
if meta_item_list.len() == 1 {
if let Some(ident) = meta_item.ident() {
if let Some(lit) = meta_item_list[0].literal() {
return Some((ident.name, lit));
}
}
2019-12-22 17:42:04 -05:00
}
None
})
})
}
/// Gets a list of inner meta items from a list `MetaItem` type.
pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
}
/// Returns `true` if the variant is `MetaItem`.
pub fn is_meta_item(&self) -> bool {
self.meta_item().is_some()
}
/// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
pub fn is_word(&self) -> bool {
self.meta_item().map_or(false, |meta_item| meta_item.is_word())
}
/// Returns `true` if `self` is a `MetaItem` and the meta item is a `ValueString`.
pub fn is_value_str(&self) -> bool {
self.value_str().is_some()
}
/// Returns `true` if `self` is a `MetaItem` and the meta item is a list.
pub fn is_meta_item_list(&self) -> bool {
self.meta_item_list().is_some()
}
}
2016-08-23 03:54:53 +00:00
impl Attribute {
pub fn has_name(&self, name: Symbol) -> bool {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(ref item, _) => item.path == name,
AttrKind::DocComment(..) => false,
}
}
/// For a single-segment attribute, returns its name; otherwise, returns `None`.
pub fn ident(&self) -> Option<Ident> {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(ref item, _) => {
if item.path.segments.len() == 1 {
Some(item.path.segments[0].ident)
} else {
None
}
}
AttrKind::DocComment(..) => None,
}
}
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or_else(Ident::invalid).name
}
pub fn value_str(&self) -> Option<Symbol> {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(ref item, _) => item.meta(self.span).and_then(|meta| meta.value_str()),
2019-12-07 21:28:29 +03:00
AttrKind::DocComment(..) => None,
}
}
pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(ref item, _) => match item.meta(self.span) {
2019-12-22 17:42:04 -05:00
Some(MetaItem { kind: MetaItemKind::List(list), .. }) => Some(list),
_ => None,
},
AttrKind::DocComment(..) => None,
}
}
pub fn is_word(&self) -> bool {
2020-11-05 20:27:48 +03:00
if let AttrKind::Normal(item, _) = &self.kind {
matches!(item.args, MacArgs::Empty)
} else {
false
}
}
2016-08-23 03:54:53 +00:00
pub fn is_meta_item_list(&self) -> bool {
self.meta_item_list().is_some()
}
/// Indicates if the attribute is a `ValueString`.
2016-08-23 03:54:53 +00:00
pub fn is_value_str(&self) -> bool {
self.value_str().is_some()
}
}
2016-08-23 03:54:53 +00:00
impl MetaItem {
/// For a single-segment meta item, returns its name; otherwise, returns `None`.
pub fn ident(&self) -> Option<Ident> {
2019-12-22 17:42:04 -05:00
if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
}
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or_else(Ident::invalid).name
2018-01-30 14:30:39 +09:00
}
// Example:
// #[attribute(name = "value")]
// ^^^^^^^^^^^^^^
pub fn name_value_literal(&self) -> Option<&Lit> {
match &self.kind {
MetaItemKind::NameValue(v) => Some(v),
_ => None,
}
}
pub fn value_str(&self) -> Option<Symbol> {
match self.kind {
2019-12-22 17:42:04 -05:00
MetaItemKind::NameValue(ref v) => match v.kind {
LitKind::Str(ref s, _) => Some(*s),
_ => None,
},
2019-12-22 17:42:04 -05:00
_ => None,
}
}
2016-08-23 03:54:53 +00:00
pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
match self.kind {
MetaItemKind::List(ref l) => Some(&l[..]),
2019-12-22 17:42:04 -05:00
_ => None,
}
}
2016-08-23 03:54:53 +00:00
pub fn is_word(&self) -> bool {
match self.kind {
MetaItemKind::Word => true,
_ => false,
}
}
pub fn has_name(&self, name: Symbol) -> bool {
self.path == name
}
2016-08-23 03:54:53 +00:00
pub fn is_value_str(&self) -> bool {
self.value_str().is_some()
}
}
impl AttrItem {
pub fn span(&self) -> Span {
self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
}
pub fn meta(&self, span: Span) -> Option<MetaItem> {
Some(MetaItem {
path: self.path.clone(),
kind: MetaItemKind::from_mac_args(&self.args)?,
span,
})
}
}
impl Attribute {
pub fn is_doc_comment(&self) -> bool {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(..) => false,
AttrKind::DocComment(..) => true,
}
}
2019-12-07 21:28:29 +03:00
pub fn doc_str(&self) -> Option<Symbol> {
match self.kind {
AttrKind::DocComment(.., data) => Some(data),
2020-11-05 20:27:48 +03:00
AttrKind::Normal(ref item, _) if item.path == sym::doc => {
2019-12-07 21:28:29 +03:00
item.meta(self.span).and_then(|meta| meta.value_str())
}
_ => None,
}
}
pub fn get_normal_item(&self) -> &AttrItem {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(ref item, _) => item,
AttrKind::DocComment(..) => panic!("unexpected doc comment"),
}
}
pub fn unwrap_normal_item(self) -> AttrItem {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(item, _) => item,
AttrKind::DocComment(..) => panic!("unexpected doc comment"),
}
}
/// Extracts the MetaItem from inside this Attribute.
pub fn meta(&self) -> Option<MetaItem> {
match self.kind {
2020-11-05 20:27:48 +03:00
AttrKind::Normal(ref item, _) => item.meta(self.span),
2019-12-07 21:28:29 +03:00
AttrKind::DocComment(..) => None,
}
}
2020-11-05 20:27:48 +03:00
pub fn tokens(&self) -> TokenStream {
match self.kind {
AttrKind::Normal(_, ref tokens) => tokens
.as_ref()
.unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self))
.create_token_stream(),
AttrKind::DocComment(comment_kind, data) => TokenStream::from(TokenTree::Token(
Token::new(token::DocComment(comment_kind, self.style, data), self.span),
)),
}
}
}
/* Constructors */
pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> MetaItem {
let lit_kind = LitKind::Str(str, ast::StrStyle::Cooked);
mk_name_value_item(ident, lit_kind, str_span)
}
pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
let lit = Lit::from_lit_kind(lit_kind, lit_span);
let span = ident.span.to(lit_span);
MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
}
2019-08-04 17:59:06 -04:00
pub fn mk_list_item(ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) }
}
pub fn mk_word_item(ident: Ident) -> MetaItem {
MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
}
2018-01-30 14:30:39 +09:00
pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
NestedMetaItem::MetaItem(mk_word_item(ident))
}
2019-08-04 19:35:29 -04:00
crate fn mk_attr_id() -> AttrId {
use std::sync::atomic::AtomicU32;
2017-12-03 14:03:28 +01:00
use std::sync::atomic::Ordering;
static NEXT_ATTR_ID: AtomicU32 = AtomicU32::new(0);
2017-12-03 14:03:28 +01:00
let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
assert!(id != u32::MAX);
AttrId::from_u32(id)
2014-05-20 00:07:24 -07:00
}
pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attribute {
2020-11-05 20:27:48 +03:00
mk_attr_from_item(AttrItem { path, args, tokens: None }, None, style, span)
2019-10-10 10:26:10 +02:00
}
2020-11-05 20:27:48 +03:00
pub fn mk_attr_from_item(
item: AttrItem,
tokens: Option<LazyTokenStream>,
style: AttrStyle,
span: Span,
) -> Attribute {
Attribute { kind: AttrKind::Normal(item, tokens), id: mk_attr_id(), style, span }
}
/// Returns an inner attribute with the given value and span.
pub fn mk_attr_inner(item: MetaItem) -> Attribute {
mk_attr(AttrStyle::Inner, item.path, item.kind.mac_args(item.span), item.span)
}
/// Returns an outer attribute with the given value and span.
pub fn mk_attr_outer(item: MetaItem) -> Attribute {
mk_attr(AttrStyle::Outer, item.path, item.kind.mac_args(item.span), item.span)
}
pub fn mk_doc_comment(
comment_kind: CommentKind,
style: AttrStyle,
data: Symbol,
span: Span,
) -> Attribute {
2020-11-05 20:27:48 +03:00
Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span }
}
pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
items.iter().any(|item| item.has_name(name))
}
impl MetaItem {
fn token_trees_and_spacings(&self) -> Vec<TreeAndSpacing> {
2018-01-30 14:30:39 +09:00
let mut idents = vec![];
let mut last_pos = BytePos(0_u32);
for (i, segment) in self.path.segments.iter().enumerate() {
2018-01-30 14:30:39 +09:00
let is_first = i == 0;
if !is_first {
2019-12-22 17:42:04 -05:00
let mod_sep_span =
Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt());
idents.push(TokenTree::token(token::ModSep, mod_sep_span).into());
2018-01-30 14:30:39 +09:00
}
idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident)).into());
2018-04-17 15:33:39 +02:00
last_pos = segment.ident.span.hi();
2018-01-30 14:30:39 +09:00
}
idents.extend(self.kind.token_trees_and_spacings(self.span));
idents
}
fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
2019-12-22 17:42:04 -05:00
where
I: Iterator<Item = TokenTree>,
{
2018-04-24 16:57:41 +02:00
// FIXME: Share code with `parse_path`.
let path = match tokens.next().map(TokenTree::uninterpolate) {
Some(TokenTree::Token(Token {
kind: kind @ (token::Ident(..) | token::ModSep),
span,
})) => 'arm: {
let mut segments = if let token::Ident(name, _) = kind {
2019-12-22 17:42:04 -05:00
if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek()
{
tokens.next();
vec![PathSegment::from_ident(Ident::new(name, span))]
} else {
break 'arm Path::from_ident(Ident::new(name, span));
2018-01-30 14:30:39 +09:00
}
} else {
vec![PathSegment::path_root(span)]
};
loop {
2019-12-22 17:42:04 -05:00
if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span })) =
tokens.next().map(TokenTree::uninterpolate)
2019-12-22 17:42:04 -05:00
{
segments.push(PathSegment::from_ident(Ident::new(name, span)));
} else {
return None;
}
2019-12-22 17:42:04 -05:00
if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek()
{
tokens.next();
} else {
break;
}
2018-01-30 14:30:39 +09:00
}
let span = span.with_hi(segments.last().unwrap().ident.span.hi());
2020-08-21 18:51:23 -04:00
Path { span, segments, tokens: None }
2018-01-30 14:30:39 +09:00
}
2020-07-01 13:16:49 +03:00
Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. })) => match *nt {
token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span),
2018-01-30 14:30:39 +09:00
token::Nonterminal::NtPath(ref path) => path.clone(),
2017-03-29 07:17:18 +00:00
_ => return None,
2017-03-08 23:13:35 +00:00
},
_ => return None,
};
2017-07-31 23:04:34 +03:00
let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
let kind = MetaItemKind::from_tokens(tokens)?;
let hi = match kind {
2017-07-31 23:04:34 +03:00
MetaItemKind::NameValue(ref lit) => lit.span.hi(),
MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
_ => path.span.hi(),
};
let span = path.span.with_hi(hi);
Some(MetaItem { path, kind, span })
}
}
impl MetaItemKind {
pub fn mac_args(&self, span: Span) -> MacArgs {
match self {
MetaItemKind::Word => MacArgs::Empty,
MetaItemKind::NameValue(lit) => MacArgs::Eq(span, lit.token_tree().into()),
MetaItemKind::List(list) => {
let mut tts = Vec::new();
for (i, item) in list.iter().enumerate() {
if i > 0 {
tts.push(TokenTree::token(token::Comma, span).into());
}
tts.extend(item.token_trees_and_spacings())
}
MacArgs::Delimited(
2019-12-22 17:42:04 -05:00
DelimSpan::from_single(span),
MacDelimiter::Parenthesis,
TokenStream::new(tts),
)
}
}
}
fn token_trees_and_spacings(&self, span: Span) -> Vec<TreeAndSpacing> {
match *self {
MetaItemKind::Word => vec![],
MetaItemKind::NameValue(ref lit) => {
2019-12-22 17:42:04 -05:00
vec![TokenTree::token(token::Eq, span).into(), lit.token_tree().into()]
}
MetaItemKind::List(ref list) => {
let mut tokens = Vec::new();
for (i, item) in list.iter().enumerate() {
if i > 0 {
tokens.push(TokenTree::token(token::Comma, span).into());
}
tokens.extend(item.token_trees_and_spacings())
}
vec![
TokenTree::Delimited(
DelimSpan::from_single(span),
token::Paren,
TokenStream::new(tokens),
2019-12-22 17:42:04 -05:00
)
.into(),
]
}
}
}
fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
let mut tokens = tokens.into_trees().peekable();
let mut result = Vec::new();
while let Some(..) = tokens.peek() {
let item = NestedMetaItem::from_tokens(&mut tokens)?;
result.push(item);
match tokens.next() {
None | Some(TokenTree::Token(Token { kind: token::Comma, .. })) => {}
_ => return None,
}
}
Some(MetaItemKind::List(result))
}
fn name_value_from_tokens(
tokens: &mut impl Iterator<Item = TokenTree>,
) -> Option<MetaItemKind> {
match tokens.next() {
Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => {
MetaItemKind::name_value_from_tokens(&mut inner_tokens.trees())
}
2019-12-22 17:42:04 -05:00
Some(TokenTree::Token(token)) => {
Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
}
_ => None,
}
}
fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
match args {
2019-12-22 17:42:04 -05:00
MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
MetaItemKind::list_from_tokens(tokens.clone())
}
MacArgs::Delimited(..) => None,
MacArgs::Eq(_, tokens) => {
assert!(tokens.len() == 1);
MetaItemKind::name_value_from_tokens(&mut tokens.trees())
}
MacArgs::Empty => Some(MetaItemKind::Word),
}
}
fn from_tokens(
tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>,
) -> Option<MetaItemKind> {
match tokens.peek() {
Some(TokenTree::Delimited(_, token::Paren, inner_tokens)) => {
let inner_tokens = inner_tokens.clone();
tokens.next();
MetaItemKind::list_from_tokens(inner_tokens)
}
Some(TokenTree::Delimited(..)) => None,
Some(TokenTree::Token(Token { kind: token::Eq, .. })) => {
tokens.next();
MetaItemKind::name_value_from_tokens(tokens)
}
_ => Some(MetaItemKind::Word),
}
}
}
impl NestedMetaItem {
pub fn span(&self) -> Span {
match *self {
NestedMetaItem::MetaItem(ref item) => item.span,
NestedMetaItem::Literal(ref lit) => lit.span,
}
}
fn token_trees_and_spacings(&self) -> Vec<TreeAndSpacing> {
match *self {
NestedMetaItem::MetaItem(ref item) => item.token_trees_and_spacings(),
NestedMetaItem::Literal(ref lit) => vec![lit.token_tree().into()],
}
}
fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
2019-12-22 17:42:04 -05:00
where
I: Iterator<Item = TokenTree>,
{
match tokens.peek() {
Some(TokenTree::Token(token)) => {
if let Ok(lit) = Lit::from_token(token) {
tokens.next();
return Some(NestedMetaItem::Literal(lit));
}
}
Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => {
let inner_tokens = inner_tokens.clone();
tokens.next();
return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
}
_ => {}
}
MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
}
}
2016-05-18 07:25:44 +00:00
pub trait HasAttrs: Sized {
2020-01-11 12:33:11 +01:00
fn attrs(&self) -> &[Attribute];
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>));
2016-05-18 07:25:44 +00:00
}
impl<T: HasAttrs> HasAttrs for Spanned<T> {
2020-01-11 12:33:11 +01:00
fn attrs(&self) -> &[Attribute] {
2019-12-22 17:42:04 -05:00
self.node.attrs()
}
2020-01-11 12:33:11 +01:00
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
self.node.visit_attrs(f);
}
}
2016-05-18 07:25:44 +00:00
impl HasAttrs for Vec<Attribute> {
fn attrs(&self) -> &[Attribute] {
self
2016-05-18 07:25:44 +00:00
}
2020-01-11 12:33:11 +01:00
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
2016-05-18 07:25:44 +00:00
f(self)
}
}
2019-12-03 16:38:34 +01:00
impl HasAttrs for AttrVec {
2016-05-18 07:25:44 +00:00
fn attrs(&self) -> &[Attribute] {
self
2016-05-18 07:25:44 +00:00
}
2020-01-11 12:33:11 +01:00
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
visit_clobber(self, |this| {
let mut vec = this.into();
f(&mut vec);
vec.into()
});
}
}
2016-05-18 07:25:44 +00:00
impl<T: HasAttrs + 'static> HasAttrs for P<T> {
fn attrs(&self) -> &[Attribute] {
(**self).attrs()
}
2020-01-11 12:33:11 +01:00
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
(**self).visit_attrs(f);
}
}
2016-05-18 07:25:44 +00:00
impl HasAttrs for StmtKind {
fn attrs(&self) -> &[Attribute] {
match *self {
2016-06-17 02:30:01 +00:00
StmtKind::Local(ref local) => local.attrs(),
StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
Fix inconsistencies in handling of inert attributes on statements When the 'early' and 'late' visitors visit an attribute target, they activate any lint attributes (e.g. `#[allow]`) that apply to it. This can affect warnings emitted on sibiling attributes. For example, the following code does not produce an `unused_attributes` for `#[inline]`, since the sibiling `#[allow(unused_attributes)]` suppressed the warning. ```rust trait Foo { #[allow(unused_attributes)] #[inline] fn first(); #[inline] #[allow(unused_attributes)] fn second(); } ``` However, we do not do this for statements - instead, the lint attributes only become active when we visit the struct nested inside `StmtKind` (e.g. `Item`). Currently, this is difficult to observe due to another issue - the `HasAttrs` impl for `StmtKind` ignores attributes for `StmtKind::Item`. As a result, the `unused_doc_comments` lint will never see attributes on item statements. This commit makes two interrelated fixes to the handling of inert (non-proc-macro) attributes on statements: * The `HasAttr` impl for `StmtKind` now returns attributes for `StmtKind::Item`, treating it just like every other `StmtKind` variant. The only place relying on the old behavior was macro which has been updated to explicitly ignore attributes on item statements. This allows the `unused_doc_comments` lint to fire for item statements. * The `early` and `late` lint visitors now activate lint attributes when invoking the callback for `Stmt`. This ensures that a lint attribute (e.g. `#[allow(unused_doc_comments)]`) can be applied to sibiling attributes on an item statement. For now, the `unused_doc_comments` lint is explicitly disabled on item statements, which preserves the current behavior. The exact locatiosn where this lint should fire are being discussed in PR #78306
2020-10-23 18:17:00 -04:00
StmtKind::Item(ref item) => item.attrs(),
StmtKind::Empty => &[],
StmtKind::MacCall(ref mac) => mac.attrs.attrs(),
2016-05-18 07:25:44 +00:00
}
}
2020-01-11 12:33:11 +01:00
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
2016-05-18 07:25:44 +00:00
match self {
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
StmtKind::Local(local) => local.visit_attrs(f),
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr.visit_attrs(f),
Fix inconsistencies in handling of inert attributes on statements When the 'early' and 'late' visitors visit an attribute target, they activate any lint attributes (e.g. `#[allow]`) that apply to it. This can affect warnings emitted on sibiling attributes. For example, the following code does not produce an `unused_attributes` for `#[inline]`, since the sibiling `#[allow(unused_attributes)]` suppressed the warning. ```rust trait Foo { #[allow(unused_attributes)] #[inline] fn first(); #[inline] #[allow(unused_attributes)] fn second(); } ``` However, we do not do this for statements - instead, the lint attributes only become active when we visit the struct nested inside `StmtKind` (e.g. `Item`). Currently, this is difficult to observe due to another issue - the `HasAttrs` impl for `StmtKind` ignores attributes for `StmtKind::Item`. As a result, the `unused_doc_comments` lint will never see attributes on item statements. This commit makes two interrelated fixes to the handling of inert (non-proc-macro) attributes on statements: * The `HasAttr` impl for `StmtKind` now returns attributes for `StmtKind::Item`, treating it just like every other `StmtKind` variant. The only place relying on the old behavior was macro which has been updated to explicitly ignore attributes on item statements. This allows the `unused_doc_comments` lint to fire for item statements. * The `early` and `late` lint visitors now activate lint attributes when invoking the callback for `Stmt`. This ensures that a lint attribute (e.g. `#[allow(unused_doc_comments)]`) can be applied to sibiling attributes on an item statement. For now, the `unused_doc_comments` lint is explicitly disabled on item statements, which preserves the current behavior. The exact locatiosn where this lint should fire are being discussed in PR #78306
2020-10-23 18:17:00 -04:00
StmtKind::Item(item) => item.visit_attrs(f),
StmtKind::Empty => {}
2020-02-29 19:32:20 +03:00
StmtKind::MacCall(mac) => {
mac.attrs.visit_attrs(f);
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
}
2016-05-18 07:25:44 +00:00
}
}
}
impl HasAttrs for Stmt {
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
fn attrs(&self) -> &[ast::Attribute] {
2019-09-26 17:34:50 +01:00
self.kind.attrs()
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
}
2020-01-11 12:33:11 +01:00
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
2019-09-26 17:34:50 +01:00
self.kind.visit_attrs(f);
}
}
macro_rules! derive_has_attrs {
($($ty:path),*) => { $(
2016-05-18 07:25:44 +00:00
impl HasAttrs for $ty {
fn attrs(&self) -> &[Attribute] {
&self.attrs
2016-05-18 07:25:44 +00:00
}
2020-01-11 12:33:11 +01:00
fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
Overhaul `syntax::fold::Folder`. This commit changes `syntax::fold::Folder` from a functional style (where most methods take a `T` and produce a new `T`) to a more imperative style (where most methods take and modify a `&mut T`), and renames it `syntax::mut_visit::MutVisitor`. The first benefit is speed. The functional style does not require any reallocations, due to the use of `P::map` and `MoveMap::move_{,flat_}map`. However, every field in the AST must be overwritten; even those fields that are unchanged are overwritten with the same value. This causes a lot of unnecessary memory writes. The imperative style reduces instruction counts by 1--3% across a wide range of workloads, particularly incremental workloads. The second benefit is conciseness; the imperative style is usually more concise. E.g. compare the old functional style: ``` fn fold_abc(&mut self, abc: ABC) { ABC { a: fold_a(abc.a), b: fold_b(abc.b), c: abc.c, } } ``` with the imperative style: ``` fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) { visit_a(a); visit_b(b); } ``` (The reductions get larger in more complex examples.) Overall, the patch removes over 200 lines of code -- even though the new code has more comments -- and a lot of the remaining lines have fewer characters. Some notes: - The old style used methods called `fold_*`. The new style mostly uses methods called `visit_*`, but there are a few methods that map a `T` to something other than a `T`, which are called `flat_map_*` (`T` maps to multiple `T`s) or `filter_map_*` (`T` maps to 0 or 1 `T`s). - `move_map.rs`/`MoveMap`/`move_map`/`move_flat_map` are renamed `map_in_place.rs`/`MapInPlace`/`map_in_place`/`flat_map_in_place` to reflect their slightly changed signatures. - Although this commit renames the `fold` module as `mut_visit`, it keeps it in the `fold.rs` file, so as not to confuse git. The next commit will rename the file.
2019-02-05 15:20:55 +11:00
self.attrs.visit_attrs(f);
2016-05-18 07:25:44 +00:00
}
}
)* }
}
derive_has_attrs! {
Item, Expr, Local, ast::AssocItem, ast::ForeignItem, ast::StructField, ast::Arm,
2020-01-11 12:33:11 +01:00
ast::Field, ast::FieldPat, ast::Variant, ast::Param, GenericParam
2016-05-18 07:25:44 +00:00
}