]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/attr/mod.rs
b7be94dde480eb205e41db5aeca2718d1ce1f02d
[rust.git] / compiler / rustc_ast / src / attr / mod.rs
1 //! Functions dealing with attributes and meta items.
2
3 use crate::ast;
4 use crate::ast::{AttrId, AttrItem, AttrKind, AttrStyle, Attribute};
5 use crate::ast::{Lit, LitKind};
6 use crate::ast::{MacArgs, MacArgsEq, MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem};
7 use crate::ast::{Path, PathSegment};
8 use crate::ptr::P;
9 use crate::token::{self, CommentKind, Delimiter, Token};
10 use crate::tokenstream::{DelimSpan, Spacing, TokenTree};
11 use crate::tokenstream::{LazyAttrTokenStream, TokenStream};
12 use crate::util::comments;
13 use rustc_data_structures::sync::WorkerLocal;
14 use rustc_index::bit_set::GrowableBitSet;
15 use rustc_span::source_map::BytePos;
16 use rustc_span::symbol::{sym, Ident, Symbol};
17 use rustc_span::Span;
18 use std::cell::Cell;
19 use std::iter;
20 #[cfg(debug_assertions)]
21 use std::ops::BitXor;
22 #[cfg(debug_assertions)]
23 use std::sync::atomic::{AtomicU32, Ordering};
24 use thin_vec::thin_vec;
25
26 pub struct MarkedAttrs(GrowableBitSet<AttrId>);
27
28 impl MarkedAttrs {
29     // We have no idea how many attributes there will be, so just
30     // initiate the vectors with 0 bits. We'll grow them as necessary.
31     pub fn new() -> Self {
32         MarkedAttrs(GrowableBitSet::new_empty())
33     }
34
35     pub fn mark(&mut self, attr: &Attribute) {
36         self.0.insert(attr.id);
37     }
38
39     pub fn is_marked(&self, attr: &Attribute) -> bool {
40         self.0.contains(attr.id)
41     }
42 }
43
44 impl NestedMetaItem {
45     /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
46     pub fn meta_item(&self) -> Option<&MetaItem> {
47         match self {
48             NestedMetaItem::MetaItem(item) => Some(item),
49             _ => None,
50         }
51     }
52
53     /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
54     pub fn literal(&self) -> Option<&Lit> {
55         match self {
56             NestedMetaItem::Literal(lit) => Some(lit),
57             _ => None,
58         }
59     }
60
61     /// Returns `true` if this list item is a MetaItem with a name of `name`.
62     pub fn has_name(&self, name: Symbol) -> bool {
63         self.meta_item().map_or(false, |meta_item| meta_item.has_name(name))
64     }
65
66     /// For a single-segment meta item, returns its name; otherwise, returns `None`.
67     pub fn ident(&self) -> Option<Ident> {
68         self.meta_item().and_then(|meta_item| meta_item.ident())
69     }
70     pub fn name_or_empty(&self) -> Symbol {
71         self.ident().unwrap_or_else(Ident::empty).name
72     }
73
74     /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
75     /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
76     pub fn value_str(&self) -> Option<Symbol> {
77         self.meta_item().and_then(|meta_item| meta_item.value_str())
78     }
79
80     /// Returns a name and single literal value tuple of the `MetaItem`.
81     pub fn name_value_literal(&self) -> Option<(Symbol, &Lit)> {
82         self.meta_item().and_then(|meta_item| {
83             meta_item.meta_item_list().and_then(|meta_item_list| {
84                 if meta_item_list.len() == 1
85                     && let Some(ident) = meta_item.ident()
86                     && let Some(lit) = meta_item_list[0].literal()
87                 {
88                     return Some((ident.name, lit));
89                 }
90                 None
91             })
92         })
93     }
94
95     /// Gets a list of inner meta items from a list `MetaItem` type.
96     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
97         self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
98     }
99
100     /// Returns `true` if the variant is `MetaItem`.
101     pub fn is_meta_item(&self) -> bool {
102         self.meta_item().is_some()
103     }
104
105     /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
106     pub fn is_word(&self) -> bool {
107         self.meta_item().map_or(false, |meta_item| meta_item.is_word())
108     }
109
110     /// See [`MetaItem::name_value_literal_span`].
111     pub fn name_value_literal_span(&self) -> Option<Span> {
112         self.meta_item()?.name_value_literal_span()
113     }
114 }
115
116 impl Attribute {
117     #[inline]
118     pub fn has_name(&self, name: Symbol) -> bool {
119         match &self.kind {
120             AttrKind::Normal(normal) => normal.item.path == name,
121             AttrKind::DocComment(..) => false,
122         }
123     }
124
125     /// For a single-segment attribute, returns its name; otherwise, returns `None`.
126     pub fn ident(&self) -> Option<Ident> {
127         match &self.kind {
128             AttrKind::Normal(normal) => {
129                 if let [ident] = &*normal.item.path.segments {
130                     Some(ident.ident)
131                 } else {
132                     None
133                 }
134             }
135             AttrKind::DocComment(..) => None,
136         }
137     }
138     pub fn name_or_empty(&self) -> Symbol {
139         self.ident().unwrap_or_else(Ident::empty).name
140     }
141
142     pub fn value_str(&self) -> Option<Symbol> {
143         match &self.kind {
144             AttrKind::Normal(normal) => normal.item.meta_kind().and_then(|kind| kind.value_str()),
145             AttrKind::DocComment(..) => None,
146         }
147     }
148
149     pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
150         match &self.kind {
151             AttrKind::Normal(normal) => match normal.item.meta_kind() {
152                 Some(MetaItemKind::List(list)) => Some(list),
153                 _ => None,
154             },
155             AttrKind::DocComment(..) => None,
156         }
157     }
158
159     pub fn is_word(&self) -> bool {
160         if let AttrKind::Normal(normal) = &self.kind {
161             matches!(normal.item.args, MacArgs::Empty)
162         } else {
163             false
164         }
165     }
166 }
167
168 impl MetaItem {
169     /// For a single-segment meta item, returns its name; otherwise, returns `None`.
170     pub fn ident(&self) -> Option<Ident> {
171         if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
172     }
173     pub fn name_or_empty(&self) -> Symbol {
174         self.ident().unwrap_or_else(Ident::empty).name
175     }
176
177     // Example:
178     //     #[attribute(name = "value")]
179     //                 ^^^^^^^^^^^^^^
180     pub fn name_value_literal(&self) -> Option<&Lit> {
181         match &self.kind {
182             MetaItemKind::NameValue(v) => Some(v),
183             _ => None,
184         }
185     }
186
187     pub fn value_str(&self) -> Option<Symbol> {
188         self.kind.value_str()
189     }
190
191     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
192         match &self.kind {
193             MetaItemKind::List(l) => Some(&**l),
194             _ => None,
195         }
196     }
197
198     pub fn is_word(&self) -> bool {
199         matches!(self.kind, MetaItemKind::Word)
200     }
201
202     pub fn has_name(&self, name: Symbol) -> bool {
203         self.path == name
204     }
205
206     /// This is used in case you want the value span instead of the whole attribute. Example:
207     ///
208     /// ```text
209     /// #[doc(alias = "foo")]
210     /// ```
211     ///
212     /// In here, it'll return a span for `"foo"`.
213     pub fn name_value_literal_span(&self) -> Option<Span> {
214         Some(self.name_value_literal()?.span)
215     }
216 }
217
218 impl AttrItem {
219     pub fn span(&self) -> Span {
220         self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
221     }
222
223     pub fn meta(&self, span: Span) -> Option<MetaItem> {
224         Some(MetaItem {
225             path: self.path.clone(),
226             kind: MetaItemKind::from_mac_args(&self.args)?,
227             span,
228         })
229     }
230
231     pub fn meta_kind(&self) -> Option<MetaItemKind> {
232         MetaItemKind::from_mac_args(&self.args)
233     }
234 }
235
236 impl Attribute {
237     /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
238     /// So `#[doc = "doc"]` (which is a doc comment) and `#[doc(...)]` (which is not
239     /// a doc comment) will return `false`.
240     pub fn is_doc_comment(&self) -> bool {
241         match self.kind {
242             AttrKind::Normal(..) => false,
243             AttrKind::DocComment(..) => true,
244         }
245     }
246
247     /// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
248     /// * `///doc` returns `Some(("doc", CommentKind::Line))`.
249     /// * `/** doc */` returns `Some(("doc", CommentKind::Block))`.
250     /// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`.
251     /// * `#[doc(...)]` returns `None`.
252     pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
253         match self.kind {
254             AttrKind::DocComment(kind, data) => Some((data, kind)),
255             AttrKind::Normal(ref normal) if normal.item.path == sym::doc => normal
256                 .item
257                 .meta_kind()
258                 .and_then(|kind| kind.value_str())
259                 .map(|data| (data, CommentKind::Line)),
260             _ => None,
261         }
262     }
263
264     /// Returns the documentation if this is a doc comment or a sugared doc comment.
265     /// * `///doc` returns `Some("doc")`.
266     /// * `#[doc = "doc"]` returns `Some("doc")`.
267     /// * `#[doc(...)]` returns `None`.
268     pub fn doc_str(&self) -> Option<Symbol> {
269         match &self.kind {
270             AttrKind::DocComment(.., data) => Some(*data),
271             AttrKind::Normal(normal) if normal.item.path == sym::doc => {
272                 normal.item.meta_kind().and_then(|kind| kind.value_str())
273             }
274             _ => None,
275         }
276     }
277
278     pub fn may_have_doc_links(&self) -> bool {
279         self.doc_str().map_or(false, |s| comments::may_have_doc_links(s.as_str()))
280     }
281
282     pub fn get_normal_item(&self) -> &AttrItem {
283         match &self.kind {
284             AttrKind::Normal(normal) => &normal.item,
285             AttrKind::DocComment(..) => panic!("unexpected doc comment"),
286         }
287     }
288
289     pub fn unwrap_normal_item(self) -> AttrItem {
290         match self.kind {
291             AttrKind::Normal(normal) => normal.into_inner().item,
292             AttrKind::DocComment(..) => panic!("unexpected doc comment"),
293         }
294     }
295
296     /// Extracts the MetaItem from inside this Attribute.
297     pub fn meta(&self) -> Option<MetaItem> {
298         match &self.kind {
299             AttrKind::Normal(normal) => normal.item.meta(self.span),
300             AttrKind::DocComment(..) => None,
301         }
302     }
303
304     pub fn meta_kind(&self) -> Option<MetaItemKind> {
305         match &self.kind {
306             AttrKind::Normal(normal) => normal.item.meta_kind(),
307             AttrKind::DocComment(..) => None,
308         }
309     }
310
311     pub fn tokens(&self) -> TokenStream {
312         match &self.kind {
313             AttrKind::Normal(normal) => normal
314                 .tokens
315                 .as_ref()
316                 .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self))
317                 .to_attr_token_stream()
318                 .to_tokenstream(),
319             &AttrKind::DocComment(comment_kind, data) => TokenStream::new(vec![TokenTree::Token(
320                 Token::new(token::DocComment(comment_kind, self.style, data), self.span),
321                 Spacing::Alone,
322             )]),
323         }
324     }
325 }
326
327 /* Constructors */
328
329 pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> MetaItem {
330     let lit_kind = LitKind::Str(str, ast::StrStyle::Cooked);
331     mk_name_value_item(ident, lit_kind, str_span)
332 }
333
334 pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
335     let lit = Lit::from_lit_kind(lit_kind, lit_span);
336     let span = ident.span.to(lit_span);
337     MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
338 }
339
340 pub fn mk_list_item(ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
341     MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) }
342 }
343
344 pub fn mk_word_item(ident: Ident) -> MetaItem {
345     MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
346 }
347
348 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
349     NestedMetaItem::MetaItem(mk_word_item(ident))
350 }
351
352 pub struct AttrIdGenerator(WorkerLocal<Cell<u32>>);
353
354 #[cfg(debug_assertions)]
355 static MAX_ATTR_ID: AtomicU32 = AtomicU32::new(u32::MAX);
356
357 impl AttrIdGenerator {
358     pub fn new() -> Self {
359         // We use `(index as u32).reverse_bits()` to initialize the
360         // starting value of AttrId in each worker thread.
361         // The `index` is the index of the worker thread.
362         // This ensures that the AttrId generated in each thread is unique.
363         AttrIdGenerator(WorkerLocal::new(|index| {
364             let index: u32 = index.try_into().unwrap();
365
366             #[cfg(debug_assertions)]
367             {
368                 let max_id = ((index + 1).next_power_of_two() - 1).bitxor(u32::MAX).reverse_bits();
369                 MAX_ATTR_ID.fetch_min(max_id, Ordering::Release);
370             }
371
372             Cell::new(index.reverse_bits())
373         }))
374     }
375
376     pub fn mk_attr_id(&self) -> AttrId {
377         let id = self.0.get();
378
379         // Ensure the assigned attr_id does not overlap the bits
380         // representing the number of threads.
381         #[cfg(debug_assertions)]
382         assert!(id <= MAX_ATTR_ID.load(Ordering::Acquire));
383
384         self.0.set(id + 1);
385         AttrId::from_u32(id)
386     }
387 }
388
389 pub fn mk_attr(
390     g: &AttrIdGenerator,
391     style: AttrStyle,
392     path: Path,
393     args: MacArgs,
394     span: Span,
395 ) -> Attribute {
396     mk_attr_from_item(g, AttrItem { path, args, tokens: None }, None, style, span)
397 }
398
399 pub fn mk_attr_from_item(
400     g: &AttrIdGenerator,
401     item: AttrItem,
402     tokens: Option<LazyAttrTokenStream>,
403     style: AttrStyle,
404     span: Span,
405 ) -> Attribute {
406     Attribute {
407         kind: AttrKind::Normal(P(ast::NormalAttr { item, tokens })),
408         id: g.mk_attr_id(),
409         style,
410         span,
411     }
412 }
413
414 /// Returns an inner attribute with the given value and span.
415 pub fn mk_attr_inner(g: &AttrIdGenerator, item: MetaItem) -> Attribute {
416     mk_attr(g, AttrStyle::Inner, item.path, item.kind.mac_args(item.span), item.span)
417 }
418
419 /// Returns an outer attribute with the given value and span.
420 pub fn mk_attr_outer(g: &AttrIdGenerator, item: MetaItem) -> Attribute {
421     mk_attr(g, AttrStyle::Outer, item.path, item.kind.mac_args(item.span), item.span)
422 }
423
424 pub fn mk_doc_comment(
425     g: &AttrIdGenerator,
426     comment_kind: CommentKind,
427     style: AttrStyle,
428     data: Symbol,
429     span: Span,
430 ) -> Attribute {
431     Attribute { kind: AttrKind::DocComment(comment_kind, data), id: g.mk_attr_id(), style, span }
432 }
433
434 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
435     items.iter().any(|item| item.has_name(name))
436 }
437
438 impl MetaItem {
439     fn token_trees(&self) -> Vec<TokenTree> {
440         let mut idents = vec![];
441         let mut last_pos = BytePos(0_u32);
442         for (i, segment) in self.path.segments.iter().enumerate() {
443             let is_first = i == 0;
444             if !is_first {
445                 let mod_sep_span =
446                     Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt(), None);
447                 idents.push(TokenTree::token_alone(token::ModSep, mod_sep_span));
448             }
449             idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
450             last_pos = segment.ident.span.hi();
451         }
452         idents.extend(self.kind.token_trees(self.span));
453         idents
454     }
455
456     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
457     where
458         I: Iterator<Item = TokenTree>,
459     {
460         // FIXME: Share code with `parse_path`.
461         let path = match tokens.next().map(TokenTree::uninterpolate) {
462             Some(TokenTree::Token(
463                 Token { kind: kind @ (token::Ident(..) | token::ModSep), span },
464                 _,
465             )) => 'arm: {
466                 let mut segments = if let token::Ident(name, _) = kind {
467                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
468                         tokens.peek()
469                     {
470                         tokens.next();
471                         thin_vec![PathSegment::from_ident(Ident::new(name, span))]
472                     } else {
473                         break 'arm Path::from_ident(Ident::new(name, span));
474                     }
475                 } else {
476                     thin_vec![PathSegment::path_root(span)]
477                 };
478                 loop {
479                     if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
480                         tokens.next().map(TokenTree::uninterpolate)
481                     {
482                         segments.push(PathSegment::from_ident(Ident::new(name, span)));
483                     } else {
484                         return None;
485                     }
486                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
487                         tokens.peek()
488                     {
489                         tokens.next();
490                     } else {
491                         break;
492                     }
493                 }
494                 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
495                 Path { span, segments, tokens: None }
496             }
497             Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. }, _)) => match &*nt {
498                 token::Nonterminal::NtMeta(item) => return item.meta(item.path.span),
499                 token::Nonterminal::NtPath(path) => (**path).clone(),
500                 _ => return None,
501             },
502             _ => return None,
503         };
504         let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
505         let kind = MetaItemKind::from_tokens(tokens)?;
506         let hi = match &kind {
507             MetaItemKind::NameValue(lit) => lit.span.hi(),
508             MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
509             _ => path.span.hi(),
510         };
511         let span = path.span.with_hi(hi);
512         Some(MetaItem { path, kind, span })
513     }
514 }
515
516 impl MetaItemKind {
517     pub fn value_str(&self) -> Option<Symbol> {
518         match self {
519             MetaItemKind::NameValue(v) => match v.kind {
520                 LitKind::Str(s, _) => Some(s),
521                 _ => None,
522             },
523             _ => None,
524         }
525     }
526
527     pub fn mac_args(&self, span: Span) -> MacArgs {
528         match self {
529             MetaItemKind::Word => MacArgs::Empty,
530             MetaItemKind::NameValue(lit) => {
531                 let expr = P(ast::Expr {
532                     id: ast::DUMMY_NODE_ID,
533                     kind: ast::ExprKind::Lit(lit.token_lit.clone()),
534                     span: lit.span,
535                     attrs: ast::AttrVec::new(),
536                     tokens: None,
537                 });
538                 MacArgs::Eq(span, MacArgsEq::Ast(expr))
539             }
540             MetaItemKind::List(list) => {
541                 let mut tts = Vec::new();
542                 for (i, item) in list.iter().enumerate() {
543                     if i > 0 {
544                         tts.push(TokenTree::token_alone(token::Comma, span));
545                     }
546                     tts.extend(item.token_trees())
547                 }
548                 MacArgs::Delimited(
549                     DelimSpan::from_single(span),
550                     MacDelimiter::Parenthesis,
551                     TokenStream::new(tts),
552                 )
553             }
554         }
555     }
556
557     fn token_trees(&self, span: Span) -> Vec<TokenTree> {
558         match self {
559             MetaItemKind::Word => vec![],
560             MetaItemKind::NameValue(lit) => {
561                 vec![
562                     TokenTree::token_alone(token::Eq, span),
563                     TokenTree::Token(lit.to_token(), Spacing::Alone),
564                 ]
565             }
566             MetaItemKind::List(list) => {
567                 let mut tokens = Vec::new();
568                 for (i, item) in list.iter().enumerate() {
569                     if i > 0 {
570                         tokens.push(TokenTree::token_alone(token::Comma, span));
571                     }
572                     tokens.extend(item.token_trees())
573                 }
574                 vec![TokenTree::Delimited(
575                     DelimSpan::from_single(span),
576                     Delimiter::Parenthesis,
577                     TokenStream::new(tokens),
578                 )]
579             }
580         }
581     }
582
583     fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
584         let mut tokens = tokens.into_trees().peekable();
585         let mut result = Vec::new();
586         while tokens.peek().is_some() {
587             let item = NestedMetaItem::from_tokens(&mut tokens)?;
588             result.push(item);
589             match tokens.next() {
590                 None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
591                 _ => return None,
592             }
593         }
594         Some(MetaItemKind::List(result))
595     }
596
597     fn name_value_from_tokens(
598         tokens: &mut impl Iterator<Item = TokenTree>,
599     ) -> Option<MetaItemKind> {
600         match tokens.next() {
601             Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
602                 MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
603             }
604             Some(TokenTree::Token(token, _)) => {
605                 Lit::from_token(&token).map(MetaItemKind::NameValue)
606             }
607             _ => None,
608         }
609     }
610
611     fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
612         match args {
613             MacArgs::Empty => Some(MetaItemKind::Word),
614             MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
615                 MetaItemKind::list_from_tokens(tokens.clone())
616             }
617             MacArgs::Delimited(..) => None,
618             MacArgs::Eq(_, MacArgsEq::Ast(expr)) => match expr.kind {
619                 ast::ExprKind::Lit(token_lit) => Some(MetaItemKind::NameValue(
620                     Lit::from_token_lit(token_lit, expr.span).expect("token_lit in from_mac_args"),
621                 )),
622                 _ => None,
623             },
624             MacArgs::Eq(_, MacArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
625         }
626     }
627
628     fn from_tokens(
629         tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>,
630     ) -> Option<MetaItemKind> {
631         match tokens.peek() {
632             Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => {
633                 let inner_tokens = inner_tokens.clone();
634                 tokens.next();
635                 MetaItemKind::list_from_tokens(inner_tokens)
636             }
637             Some(TokenTree::Delimited(..)) => None,
638             Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
639                 tokens.next();
640                 MetaItemKind::name_value_from_tokens(tokens)
641             }
642             _ => Some(MetaItemKind::Word),
643         }
644     }
645 }
646
647 impl NestedMetaItem {
648     pub fn span(&self) -> Span {
649         match self {
650             NestedMetaItem::MetaItem(item) => item.span,
651             NestedMetaItem::Literal(lit) => lit.span,
652         }
653     }
654
655     fn token_trees(&self) -> Vec<TokenTree> {
656         match self {
657             NestedMetaItem::MetaItem(item) => item.token_trees(),
658             NestedMetaItem::Literal(lit) => {
659                 vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
660             }
661         }
662     }
663
664     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
665     where
666         I: Iterator<Item = TokenTree>,
667     {
668         match tokens.peek() {
669             Some(TokenTree::Token(token, _))
670                 if let Some(lit) = Lit::from_token(token) =>
671             {
672                 tokens.next();
673                 return Some(NestedMetaItem::Literal(lit));
674             }
675             Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
676                 let inner_tokens = inner_tokens.clone();
677                 tokens.next();
678                 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
679             }
680             _ => {}
681         }
682         MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
683     }
684 }