Skip to content

Commit ba1751a

Browse files
committed
Avoid more MetaItem-to-Attribute conversions.
There is code for converting `Attribute` (syntactic) to `MetaItem` (semantic). There is also code for the reverse direction. The reverse direction isn't really necessary; it's currently only used when generating attributes, e.g. in `derive` code. This commit adds some new functions for creating `Attributes`s directly, without involving `MetaItem`s: `mk_attr_word`, `mk_attr_name_value_str`, `mk_attr_nested_word`, and `ExtCtxt::attr_{word,name_value_str,nested_word}`. These new methods replace the old functions for creating `Attribute`s: `mk_attr_inner`, `mk_attr_outer`, and `ExtCtxt::attribute`. Those functions took `MetaItem`s as input, and relied on many other functions that created `MetaItems`, which are also removed: `mk_name_value_item`, `mk_list_item`, `mk_word_item`, `mk_nested_word_item`, `{MetaItem,MetaItemKind,NestedMetaItem}::token_trees`, `MetaItemKind::attr_args`, `MetaItemLit::{from_lit_kind,to_token}`, `ExtCtxt::meta_word`. Overall this cuts more than 100 lines of code and makes thing simpler.
1 parent d1b61a3 commit ba1751a

File tree

20 files changed

+116
-211
lines changed

20 files changed

+116
-211
lines changed

compiler/rustc_ast/src/attr/mod.rs

+52-115
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
11
//! Functions dealing with attributes and meta items.
22
33
use crate::ast;
4-
use crate::ast::{AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, Attribute};
5-
use crate::ast::{DelimArgs, LitKind, MetaItemLit};
6-
use crate::ast::{MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem};
7-
use crate::ast::{Path, PathSegment};
4+
use crate::ast::{AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute};
5+
use crate::ast::{DelimArgs, Expr, ExprKind, LitKind, MetaItemLit};
6+
use crate::ast::{MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem, NormalAttr};
7+
use crate::ast::{Path, PathSegment, StrStyle, DUMMY_NODE_ID};
88
use crate::ptr::P;
99
use crate::token::{self, CommentKind, Delimiter, Token};
1010
use crate::tokenstream::{DelimSpan, Spacing, TokenTree};
1111
use crate::tokenstream::{LazyAttrTokenStream, TokenStream};
1212
use crate::util::comments;
1313
use rustc_data_structures::sync::WorkerLocal;
1414
use rustc_index::bit_set::GrowableBitSet;
15-
use rustc_span::source_map::BytePos;
1615
use rustc_span::symbol::{sym, Ident, Symbol};
1716
use rustc_span::Span;
1817
use std::cell::Cell;
@@ -223,11 +222,7 @@ impl AttrItem {
223222
}
224223

225224
pub fn meta(&self, span: Span) -> Option<MetaItem> {
226-
Some(MetaItem {
227-
path: self.path.clone(),
228-
kind: MetaItemKind::from_attr_args(&self.args)?,
229-
span,
230-
})
225+
Some(MetaItem { path: self.path.clone(), kind: self.meta_kind()?, span })
231226
}
232227

233228
pub fn meta_kind(&self) -> Option<MetaItemKind> {
@@ -329,26 +324,13 @@ impl Attribute {
329324
/* Constructors */
330325

331326
pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> MetaItem {
332-
let lit_kind = LitKind::Str(str, ast::StrStyle::Cooked);
333-
mk_name_value_item(ident, lit_kind, str_span)
327+
mk_name_value_item(ident, LitKind::Str(str, ast::StrStyle::Cooked), str_span)
334328
}
335329

336330
pub fn mk_name_value_item(ident: Ident, kind: LitKind, lit_span: Span) -> MetaItem {
337331
let lit = MetaItemLit { token_lit: kind.to_token_lit(), kind, span: lit_span };
338332
let span = ident.span.to(lit_span);
339-
MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
340-
}
341-
342-
pub fn mk_list_item(ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
343-
MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) }
344-
}
345-
346-
pub fn mk_word_item(ident: Ident) -> MetaItem {
347-
MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
348-
}
349-
350-
pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
351-
NestedMetaItem::MetaItem(mk_word_item(ident))
333+
MetaItem { path: Path::from_ident(ident), kind: MetaItemKind::NameValue(lit), span }
352334
}
353335

354336
pub struct AttrIdGenerator(WorkerLocal<Cell<u32>>);
@@ -406,21 +388,58 @@ pub fn mk_attr_from_item(
406388
span: Span,
407389
) -> Attribute {
408390
Attribute {
409-
kind: AttrKind::Normal(P(ast::NormalAttr { item, tokens })),
391+
kind: AttrKind::Normal(P(NormalAttr { item, tokens })),
410392
id: g.mk_attr_id(),
411393
style,
412394
span,
413395
}
414396
}
415397

416-
/// Returns an inner attribute with the given value and span.
417-
pub fn mk_attr_inner(g: &AttrIdGenerator, item: MetaItem) -> Attribute {
418-
mk_attr(g, AttrStyle::Inner, item.path, item.kind.attr_args(item.span), item.span)
398+
pub fn mk_attr_word(g: &AttrIdGenerator, style: AttrStyle, name: Symbol, span: Span) -> Attribute {
399+
let path = Path::from_ident(Ident::new(name, span));
400+
let args = AttrArgs::Empty;
401+
mk_attr(g, style, path, args, span)
402+
}
403+
404+
pub fn mk_attr_name_value_str(
405+
g: &AttrIdGenerator,
406+
style: AttrStyle,
407+
name: Symbol,
408+
val: Symbol,
409+
span: Span,
410+
) -> Attribute {
411+
let lit = LitKind::Str(val, StrStyle::Cooked).to_token_lit();
412+
let expr = P(Expr {
413+
id: DUMMY_NODE_ID,
414+
kind: ExprKind::Lit(lit),
415+
span,
416+
attrs: AttrVec::new(),
417+
tokens: None,
418+
});
419+
let path = Path::from_ident(Ident::new(name, span));
420+
let args = AttrArgs::Eq(span, AttrArgsEq::Ast(expr));
421+
mk_attr(g, style, path, args, span)
419422
}
420423

421-
/// Returns an outer attribute with the given value and span.
422-
pub fn mk_attr_outer(g: &AttrIdGenerator, item: MetaItem) -> Attribute {
423-
mk_attr(g, AttrStyle::Outer, item.path, item.kind.attr_args(item.span), item.span)
424+
pub fn mk_attr_nested_word(
425+
g: &AttrIdGenerator,
426+
style: AttrStyle,
427+
outer: Symbol,
428+
inner: Symbol,
429+
span: Span,
430+
) -> Attribute {
431+
let inner_tokens = TokenStream::new(vec![TokenTree::Token(
432+
Token::from_ast_ident(Ident::new(inner, span)),
433+
Spacing::Alone,
434+
)]);
435+
let outer_ident = Ident::new(outer, span);
436+
let path = Path::from_ident(outer_ident);
437+
let attr_args = AttrArgs::Delimited(DelimArgs {
438+
dspan: DelimSpan::from_single(span),
439+
delim: MacDelimiter::Parenthesis,
440+
tokens: inner_tokens,
441+
});
442+
mk_attr(g, style, path, attr_args, span)
424443
}
425444

426445
pub fn mk_doc_comment(
@@ -438,23 +457,6 @@ pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
438457
}
439458

440459
impl MetaItem {
441-
fn token_trees(&self) -> Vec<TokenTree> {
442-
let mut idents = vec![];
443-
let mut last_pos = BytePos(0_u32);
444-
for (i, segment) in self.path.segments.iter().enumerate() {
445-
let is_first = i == 0;
446-
if !is_first {
447-
let mod_sep_span =
448-
Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt(), None);
449-
idents.push(TokenTree::token_alone(token::ModSep, mod_sep_span));
450-
}
451-
idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
452-
last_pos = segment.ident.span.hi();
453-
}
454-
idents.extend(self.kind.token_trees(self.span));
455-
idents
456-
}
457-
458460
fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
459461
where
460462
I: Iterator<Item = TokenTree>,
@@ -526,62 +528,6 @@ impl MetaItemKind {
526528
}
527529
}
528530

529-
pub fn attr_args(&self, span: Span) -> AttrArgs {
530-
match self {
531-
MetaItemKind::Word => AttrArgs::Empty,
532-
MetaItemKind::NameValue(lit) => {
533-
let expr = P(ast::Expr {
534-
id: ast::DUMMY_NODE_ID,
535-
kind: ast::ExprKind::Lit(lit.token_lit.clone()),
536-
span: lit.span,
537-
attrs: ast::AttrVec::new(),
538-
tokens: None,
539-
});
540-
AttrArgs::Eq(span, AttrArgsEq::Ast(expr))
541-
}
542-
MetaItemKind::List(list) => {
543-
let mut tts = Vec::new();
544-
for (i, item) in list.iter().enumerate() {
545-
if i > 0 {
546-
tts.push(TokenTree::token_alone(token::Comma, span));
547-
}
548-
tts.extend(item.token_trees())
549-
}
550-
AttrArgs::Delimited(DelimArgs {
551-
dspan: DelimSpan::from_single(span),
552-
delim: MacDelimiter::Parenthesis,
553-
tokens: TokenStream::new(tts),
554-
})
555-
}
556-
}
557-
}
558-
559-
fn token_trees(&self, span: Span) -> Vec<TokenTree> {
560-
match self {
561-
MetaItemKind::Word => vec![],
562-
MetaItemKind::NameValue(lit) => {
563-
vec![
564-
TokenTree::token_alone(token::Eq, span),
565-
TokenTree::Token(lit.to_token(), Spacing::Alone),
566-
]
567-
}
568-
MetaItemKind::List(list) => {
569-
let mut tokens = Vec::new();
570-
for (i, item) in list.iter().enumerate() {
571-
if i > 0 {
572-
tokens.push(TokenTree::token_alone(token::Comma, span));
573-
}
574-
tokens.extend(item.token_trees())
575-
}
576-
vec![TokenTree::Delimited(
577-
DelimSpan::from_single(span),
578-
Delimiter::Parenthesis,
579-
TokenStream::new(tokens),
580-
)]
581-
}
582-
}
583-
}
584-
585531
fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
586532
let mut tokens = tokens.into_trees().peekable();
587533
let mut result = Vec::new();
@@ -620,7 +566,7 @@ impl MetaItemKind {
620566
}) => MetaItemKind::list_from_tokens(tokens.clone()),
621567
AttrArgs::Delimited(..) => None,
622568
AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => match expr.kind {
623-
ast::ExprKind::Lit(token_lit) => {
569+
ExprKind::Lit(token_lit) => {
624570
// Turn failures to `None`, we'll get parse errors elsewhere.
625571
MetaItemLit::from_token_lit(token_lit, expr.span)
626572
.ok()
@@ -659,15 +605,6 @@ impl NestedMetaItem {
659605
}
660606
}
661607

662-
fn token_trees(&self) -> Vec<TokenTree> {
663-
match self {
664-
NestedMetaItem::MetaItem(item) => item.token_trees(),
665-
NestedMetaItem::Lit(lit) => {
666-
vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
667-
}
668-
}
669-
}
670-
671608
fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
672609
where
673610
I: Iterator<Item = TokenTree>,

compiler/rustc_ast/src/util/literal.rs

-9
Original file line numberDiff line numberDiff line change
@@ -206,15 +206,6 @@ impl MetaItemLit {
206206
token::Lit::from_token(token)
207207
.and_then(|token_lit| MetaItemLit::from_token_lit(token_lit, token.span).ok())
208208
}
209-
210-
/// Losslessly convert a meta item literal into a token.
211-
pub fn to_token(&self) -> Token {
212-
let kind = match self.token_lit.kind {
213-
token::Bool => token::Ident(self.token_lit.symbol, false),
214-
_ => token::Literal(self.token_lit),
215-
};
216-
Token::new(kind, self.span)
217-
}
218209
}
219210

220211
fn strip_underscores(symbol: Symbol) -> Symbol {

compiler/rustc_ast_lowering/src/expr.rs

+7-10
Original file line numberDiff line numberDiff line change
@@ -1606,16 +1606,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
16061606
};
16071607

16081608
// `#[allow(unreachable_code)]`
1609-
let attr = {
1610-
// `allow(unreachable_code)`
1611-
let allow = {
1612-
let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1613-
let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1614-
let uc_nested = attr::mk_nested_word_item(uc_ident);
1615-
attr::mk_list_item(allow_ident, vec![uc_nested])
1616-
};
1617-
attr::mk_attr_outer(&self.tcx.sess.parse_sess.attr_id_generator, allow)
1618-
};
1609+
let attr = attr::mk_attr_nested_word(
1610+
&self.tcx.sess.parse_sess.attr_id_generator,
1611+
AttrStyle::Outer,
1612+
sym::allow,
1613+
sym::unreachable_code,
1614+
self.lower_span(span),
1615+
);
16191616
let attrs: AttrVec = thin_vec![attr];
16201617

16211618
// `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`

compiler/rustc_ast_pretty/src/pprust/state.rs

+11-8
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
1919
use rustc_span::edition::Edition;
2020
use rustc_span::source_map::{SourceMap, Spanned};
2121
use rustc_span::symbol::{kw, sym, Ident, IdentPrinter, Symbol};
22-
use rustc_span::{BytePos, FileName, Span};
22+
use rustc_span::{BytePos, FileName, Span, DUMMY_SP};
2323

2424
use rustc_ast::attr::AttrIdGenerator;
2525
use std::borrow::Cow;
@@ -119,17 +119,20 @@ pub fn print_crate<'a>(
119119
// of the feature gate, so we fake them up here.
120120

121121
// `#![feature(prelude_import)]`
122-
let pi_nested = attr::mk_nested_word_item(Ident::with_dummy_span(sym::prelude_import));
123-
let list = attr::mk_list_item(Ident::with_dummy_span(sym::feature), vec![pi_nested]);
124-
let fake_attr = attr::mk_attr_inner(g, list);
122+
let fake_attr = attr::mk_attr_nested_word(
123+
g,
124+
ast::AttrStyle::Inner,
125+
sym::feature,
126+
sym::prelude_import,
127+
DUMMY_SP,
128+
);
125129
s.print_attribute(&fake_attr);
126130

127131
// Currently, in Rust 2018 we don't have `extern crate std;` at the crate
128132
// root, so this is not needed, and actually breaks things.
129133
if edition == Edition::Edition2015 {
130134
// `#![no_std]`
131-
let no_std_meta = attr::mk_word_item(Ident::with_dummy_span(sym::no_std));
132-
let fake_attr = attr::mk_attr_inner(g, no_std_meta);
135+
let fake_attr = attr::mk_attr_word(g, ast::AttrStyle::Inner, sym::no_std, DUMMY_SP);
133136
s.print_attribute(&fake_attr);
134137
}
135138
}
@@ -1712,9 +1715,9 @@ impl<'a> State<'a> {
17121715
where_clause: ast::WhereClause {
17131716
has_where_token: false,
17141717
predicates: Vec::new(),
1715-
span: rustc_span::DUMMY_SP,
1718+
span: DUMMY_SP,
17161719
},
1717-
span: rustc_span::DUMMY_SP,
1720+
span: DUMMY_SP,
17181721
};
17191722
let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
17201723
self.print_fn(decl, header, name, &generics);

compiler/rustc_builtin_macros/src/alloc_error_handler.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,7 @@ fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span
9595
body,
9696
}));
9797

98-
let special = sym::rustc_std_internal_symbol;
99-
let special = cx.meta_word(span, special);
100-
let attrs = thin_vec![cx.attribute(special)];
98+
let attrs = thin_vec![cx.attr_word(sym::rustc_std_internal_symbol, span)];
10199

102100
let item = cx.item(span, Ident::from_str_and_span("__rg_oom", span), attrs, kind);
103101
cx.stmt_item(sig_span, item)

compiler/rustc_builtin_macros/src/assert/context.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
use rustc_ast::{
2-
attr,
32
ptr::P,
43
token,
54
tokenstream::{DelimSpan, TokenStream, TokenTree},
@@ -118,10 +117,7 @@ impl<'cx, 'a> Context<'cx, 'a> {
118117
self.cx.item(
119118
self.span,
120119
Ident::empty(),
121-
thin_vec![self.cx.attribute(attr::mk_list_item(
122-
Ident::new(sym::allow, self.span),
123-
vec![attr::mk_nested_word_item(Ident::new(sym::unused_imports, self.span))],
124-
))],
120+
thin_vec![self.cx.attr_nested_word(sym::allow, sym::unused_imports, self.span)],
125121
ItemKind::Use(UseTree {
126122
prefix: self.cx.path(self.span, self.cx.std_path(&[sym::asserting])),
127123
kind: UseTreeKind::Nested(vec![

compiler/rustc_builtin_macros/src/deriving/clone.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@ pub fn expand_deriving_clone(
6868
_ => cx.span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
6969
}
7070

71-
let inline = cx.meta_word(span, sym::inline);
72-
let attrs = thin_vec![cx.attribute(inline)];
71+
let attrs = thin_vec![cx.attr_word(sym::inline, span)];
7372
let trait_def = TraitDef {
7473
span,
7574
path: path_std!(clone::Clone),

compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::deriving::path_std;
55
use rustc_ast::{self as ast, MetaItem};
66
use rustc_data_structures::fx::FxHashSet;
77
use rustc_expand::base::{Annotatable, ExtCtxt};
8-
use rustc_span::symbol::{sym, Ident};
8+
use rustc_span::symbol::sym;
99
use rustc_span::Span;
1010
use thin_vec::thin_vec;
1111

@@ -18,11 +18,11 @@ pub fn expand_deriving_eq(
1818
is_const: bool,
1919
) {
2020
let span = cx.with_def_site_ctxt(span);
21-
let inline = cx.meta_word(span, sym::inline);
22-
let hidden = rustc_ast::attr::mk_nested_word_item(Ident::new(sym::hidden, span));
23-
let doc = rustc_ast::attr::mk_list_item(Ident::new(sym::doc, span), vec![hidden]);
24-
let no_coverage = cx.meta_word(span, sym::no_coverage);
25-
let attrs = thin_vec![cx.attribute(inline), cx.attribute(doc), cx.attribute(no_coverage)];
21+
let attrs = thin_vec![
22+
cx.attr_word(sym::inline, span),
23+
cx.attr_nested_word(sym::doc, sym::hidden, span),
24+
cx.attr_word(sym::no_coverage, span)
25+
];
2626
let trait_def = TraitDef {
2727
span,
2828
path: path_std!(cmp::Eq),

0 commit comments

Comments
 (0)