blob: 4fede88827bb13c7bee97551d551192cc7711049 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnayb79ee962016-09-04 09:39:20 -07009use super::*;
David Tolnayf2cfd722017-12-31 18:02:51 -050010use punctuated::Punctuated;
David Tolnayb79ee962016-09-04 09:39:20 -070011
David Tolnay4a51dc72016-10-01 00:40:31 -070012use std::iter;
13
David Tolnaye303b7c2018-05-20 16:46:35 -070014use proc_macro2::{Delimiter, Spacing, TokenStream, TokenTree};
David Tolnay9c76bcb2017-12-26 23:14:59 -050015
David Tolnay50660862018-09-01 15:42:53 -070016#[cfg(feature = "parsing")]
17use parse::{ParseStream, Result};
David Tolnay9c76bcb2017-12-26 23:14:59 -050018#[cfg(feature = "extra-traits")]
19use std::hash::{Hash, Hasher};
20#[cfg(feature = "extra-traits")]
David Tolnayc43b44e2017-12-30 23:55:54 -050021use tt::TokenStreamHelper;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070022
Alex Crichton62a0a592017-05-22 13:58:53 -070023ast_struct! {
David Tolnay23557142018-01-06 22:45:40 -080024 /// An attribute like `#[repr(transparent)]`.
25 ///
David Tolnay461d98e2018-01-07 11:07:19 -080026 /// *This type is available if Syn is built with the `"derive"` or `"full"`
27 /// feature.*
28 ///
David Tolnay23557142018-01-06 22:45:40 -080029 /// # Syntax
30 ///
31 /// Rust has six types of attributes.
32 ///
33 /// - Outer attributes like `#[repr(transparent)]`. These appear outside or
34 /// in front of the item they describe.
35 /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
36 /// of the item they describe, usually a module.
37 /// - Outer doc comments like `/// # Example`.
38 /// - Inner doc comments like `//! Please file an issue`.
39 /// - Outer block comments `/** # Example */`.
40 /// - Inner block comments `/*! Please file an issue */`.
41 ///
42 /// The `style` field of type `AttrStyle` distinguishes whether an attribute
43 /// is outer or inner. Doc comments and block comments are promoted to
David Tolnayfe583302018-08-24 16:09:34 -040044 /// attributes, as this is how they are processed by the compiler and by
45 /// `macro_rules!` macros.
David Tolnay23557142018-01-06 22:45:40 -080046 ///
47 /// The `path` field gives the possibly colon-delimited path against which
48 /// the attribute is resolved. It is equal to `"doc"` for desugared doc
49 /// comments. The `tts` field contains the rest of the attribute body as
50 /// tokens.
51 ///
52 /// ```text
53 /// #[derive(Copy)] #[crate::precondition x < 5]
54 /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~
55 /// path tts path tts
56 /// ```
57 ///
David Tolnay068120a2018-01-06 23:17:22 -080058 /// Use the [`interpret_meta`] method to try parsing the tokens of an
59 /// attribute into the structured representation that is used by convention
60 /// across most Rust libraries.
David Tolnay23557142018-01-06 22:45:40 -080061 ///
David Tolnay068120a2018-01-06 23:17:22 -080062 /// [`interpret_meta`]: #method.interpret_meta
David Tolnayd8bd15f2018-09-01 16:57:39 -070063 ///
64 /// # Parsing
65 ///
66 /// This type does not implement the [`Parse`] trait and thus cannot be
67 /// parsed directly by [`ParseStream::parse`]. Instead use
68 /// [`ParseStream::call`] with one of the two parser functions
69 /// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
70 /// which you intend to parse.
71 ///
72 /// [`Parse`]: parse/trait.Parse.html
73 /// [`ParseStream::parse`]: parse/struct.ParseBuffer.html#method.parse
74 /// [`ParseStream::call`]: parse/struct.ParseBuffer.html#method.call
75 /// [`Attribute::parse_outer`]: #method.parse_outer
76 /// [`Attribute::parse_inner`]: #method.parse_inner
77 ///
78 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -070079 /// #[macro_use]
80 /// extern crate syn;
81 ///
82 /// use syn::{Attribute, Ident};
David Tolnayd8bd15f2018-09-01 16:57:39 -070083 /// use syn::parse::{Parse, ParseStream, Result};
84 ///
85 /// // Parses a unit struct with attributes.
86 /// //
87 /// // #[path = "s.tmpl"]
88 /// // struct S;
89 /// struct UnitStruct {
90 /// attrs: Vec<Attribute>,
91 /// struct_token: Token![struct],
92 /// name: Ident,
93 /// semi_token: Token![;],
94 /// }
95 ///
96 /// impl Parse for UnitStruct {
97 /// fn parse(input: ParseStream) -> Result<Self> {
98 /// Ok(UnitStruct {
99 /// attrs: input.call(Attribute::parse_outer)?,
100 /// struct_token: input.parse()?,
101 /// name: input.parse()?,
102 /// semi_token: input.parse()?,
103 /// })
104 /// }
105 /// }
106 /// #
107 /// # fn main() {}
108 /// ```
David Tolnay9c76bcb2017-12-26 23:14:59 -0500109 pub struct Attribute #manual_extra_traits {
David Tolnayf8db7ba2017-11-11 22:52:16 -0800110 pub pound_token: Token![#],
David Tolnay4a3f59a2017-12-28 21:21:12 -0500111 pub style: AttrStyle,
David Tolnay32954ef2017-12-26 22:43:16 -0500112 pub bracket_token: token::Bracket,
Alex Crichton62a0a592017-05-22 13:58:53 -0700113 pub path: Path,
David Tolnay369f0c52017-12-27 01:50:45 -0500114 pub tts: TokenStream,
Alex Crichton62a0a592017-05-22 13:58:53 -0700115 }
David Tolnayb79ee962016-09-04 09:39:20 -0700116}
117
David Tolnay9c76bcb2017-12-26 23:14:59 -0500118#[cfg(feature = "extra-traits")]
119impl Eq for Attribute {}
120
121#[cfg(feature = "extra-traits")]
122impl PartialEq for Attribute {
123 fn eq(&self, other: &Self) -> bool {
David Tolnay65fb5662018-05-20 20:02:28 -0700124 self.style == other.style
125 && self.pound_token == other.pound_token
126 && self.bracket_token == other.bracket_token
127 && self.path == other.path
David Tolnay369f0c52017-12-27 01:50:45 -0500128 && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts)
David Tolnay9c76bcb2017-12-26 23:14:59 -0500129 }
130}
131
132#[cfg(feature = "extra-traits")]
133impl Hash for Attribute {
134 fn hash<H>(&self, state: &mut H)
David Tolnay51382052017-12-27 13:46:21 -0500135 where
136 H: Hasher,
David Tolnay9c76bcb2017-12-26 23:14:59 -0500137 {
138 self.style.hash(state);
139 self.pound_token.hash(state);
140 self.bracket_token.hash(state);
141 self.path.hash(state);
David Tolnay369f0c52017-12-27 01:50:45 -0500142 TokenStreamHelper(&self.tts).hash(state);
David Tolnay9c76bcb2017-12-26 23:14:59 -0500143 }
144}
145
David Tolnay02d77cc2016-10-02 09:52:08 -0700146impl Attribute {
David Tolnay068120a2018-01-06 23:17:22 -0800147 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
148 /// possible.
David Tolnayaaadd782018-01-06 22:58:13 -0800149 pub fn interpret_meta(&self) -> Option<Meta> {
Arnavion95f8a7a2017-04-19 03:29:56 -0700150 let name = if self.path.segments.len() == 1 {
David Tolnay56080682018-01-06 14:01:52 -0800151 &self.path.segments.first().unwrap().value().ident
Arnavion95f8a7a2017-04-19 03:29:56 -0700152 } else {
153 return None;
154 };
155
Arnavionbf395bf2017-04-15 15:35:22 -0700156 if self.tts.is_empty() {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700157 return Some(Meta::Word(name.clone()));
Arnavionbf395bf2017-04-15 15:35:22 -0700158 }
159
David Tolnay369f0c52017-12-27 01:50:45 -0500160 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
161
162 if tts.len() == 1 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700163 if let Some(meta) = Attribute::extract_meta_list(name.clone(), &tts[0]) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700164 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700165 }
166 }
167
David Tolnay369f0c52017-12-27 01:50:45 -0500168 if tts.len() == 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700169 if let Some(meta) = Attribute::extract_name_value(name.clone(), &tts[0], &tts[1]) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700170 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700171 }
172 }
173
174 None
David Tolnay02d77cc2016-10-02 09:52:08 -0700175 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700176
David Tolnay50660862018-09-01 15:42:53 -0700177 /// Parses zero or more outer attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700178 ///
179 /// *This function is available if Syn is built with the `"parsing"`
180 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700181 #[cfg(feature = "parsing")]
182 pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> {
183 let mut attrs = Vec::new();
184 while input.peek(Token![#]) {
185 attrs.push(input.call(parsing::single_parse_outer)?);
186 }
187 Ok(attrs)
188 }
189
190 /// Parses zero or more inner attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700191 ///
192 /// *This function is available if Syn is built with the `"parsing"`
193 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700194 #[cfg(feature = "parsing")]
195 pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> {
196 let mut attrs = Vec::new();
197 while input.peek(Token![#]) && input.peek2(Token![!]) {
198 attrs.push(input.call(parsing::single_parse_inner)?);
199 }
200 Ok(attrs)
201 }
202
Alex Crichton9a4dca22018-03-28 06:32:19 -0700203 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
204 let g = match *tt {
205 TokenTree::Group(ref g) => g,
206 _ => return None,
207 };
208 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700209 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700210 }
211 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
212 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
213 Some(n) => n,
214 None => return None,
215 };
216 Some(Meta::List(MetaList {
217 paren_token: token::Paren(g.span()),
218 ident: ident,
219 nested: nested,
220 }))
221 }
222
223 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
224 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700225 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700226 _ => return None,
227 };
228 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700229 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700230 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700231 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700232 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700233 }
234
235 match *b {
236 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
237 Some(Meta::NameValue(MetaNameValue {
238 ident: ident,
239 eq_token: Token![=]([a.span()]),
240 lit: Lit::new(l.clone()),
241 }))
242 }
David Tolnaya4319b72018-06-02 00:49:15 -0700243 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700244 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
245 ident: ident,
246 eq_token: Token![=]([a.span()]),
247 lit: Lit::Bool(LitBool {
248 value: v == "true",
249 span: b.span(),
250 }),
251 })),
252 _ => None,
253 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700254 _ => None,
255 }
256 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700257}
258
David Tolnayaaadd782018-01-06 22:58:13 -0800259fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700260 assert!(!tts.is_empty());
261
Alex Crichton9a4dca22018-03-28 06:32:19 -0700262 match tts[0] {
263 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800264 if lit.to_string().starts_with('/') {
265 None
266 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700267 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800268 Some((NestedMeta::Literal(lit), &tts[1..]))
269 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700270 }
271
Alex Crichtona74a1c82018-05-16 10:20:44 -0700272 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700273 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700274 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700275 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700276 }
277 }
278
279 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700280 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700281 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700282 }
283 }
284
Alex Crichtona74a1c82018-05-16 10:20:44 -0700285 Some((Meta::Word(ident.clone()).into(), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700286 }
287
David Tolnay51382052017-12-27 13:46:21 -0500288 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700289 }
290}
291
David Tolnay51382052017-12-27 13:46:21 -0500292fn list_of_nested_meta_items_from_tokens(
293 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800294) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500295 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700296 let mut first = true;
297
298 while !tts.is_empty() {
299 let prev_comma = if first {
300 first = false;
301 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700302 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700303 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700304 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700305 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700306 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700307 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700308 }
309 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700310 tts = &tts[1..];
311 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500312 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700313 }
314 Some(tok)
315 } else {
David Tolnay51382052017-12-27 13:46:21 -0500316 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700317 };
318 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
319 Some(pair) => pair,
320 None => return None,
321 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500322 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800323 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700324 }
David Tolnay56080682018-01-06 14:01:52 -0800325 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700326 tts = rest;
327 }
328
David Tolnayf2cfd722017-12-31 18:02:51 -0500329 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700330}
331
Alex Crichton62a0a592017-05-22 13:58:53 -0700332ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800333 /// Distinguishes between attributes that decorate an item and attributes
334 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800335 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800336 /// *This type is available if Syn is built with the `"derive"` or `"full"`
337 /// feature.*
338 ///
David Tolnay23557142018-01-06 22:45:40 -0800339 /// # Outer attributes
340 ///
341 /// - `#[repr(transparent)]`
342 /// - `/// # Example`
343 /// - `/** Please file an issue */`
344 ///
345 /// # Inner attributes
346 ///
347 /// - `#![feature(proc_macro)]`
348 /// - `//! # Example`
349 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700350 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700351 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700352 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800353 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700354 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700355}
356
Alex Crichton62a0a592017-05-22 13:58:53 -0700357ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800358 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700359 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800360 /// *This type is available if Syn is built with the `"derive"` or `"full"`
361 /// feature.*
362 ///
David Tolnay068120a2018-01-06 23:17:22 -0800363 /// ## Word
364 ///
365 /// A meta word is like the `test` in `#[test]`.
366 ///
367 /// ## List
368 ///
369 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
370 ///
371 /// ## NameValue
372 ///
373 /// A name-value meta is like the `path = "..."` in `#[path =
374 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800375 ///
376 /// # Syntax tree enum
377 ///
378 /// This type is a [syntax tree enum].
379 ///
380 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800381 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800382 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800383 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800384 ///
385 /// *This type is available if Syn is built with the `"derive"` or
386 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800387 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700388 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500389 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800390 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700391 }),
David Tolnay068120a2018-01-06 23:17:22 -0800392 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800393 ///
394 /// *This type is available if Syn is built with the `"derive"` or
395 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700396 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700397 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800398 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700399 pub lit: Lit,
400 }),
401 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700402}
403
David Tolnayaaadd782018-01-06 22:58:13 -0800404impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800405 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700406 ///
David Tolnay068120a2018-01-06 23:17:22 -0800407 /// For example this would return the `test` in `#[test]`, the `derive` in
408 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
409 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700410 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700411 Meta::Word(ref meta) => meta.clone(),
412 Meta::List(ref meta) => meta.ident.clone(),
413 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700414 }
415 }
David Tolnay8e661e22016-09-27 00:00:04 -0700416}
417
Alex Crichton62a0a592017-05-22 13:58:53 -0700418ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800419 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800420 ///
421 /// *This type is available if Syn is built with the `"derive"` or `"full"`
422 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800423 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800424 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
425 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800426 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500427
David Tolnay068120a2018-01-06 23:17:22 -0800428 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700429 pub Literal(Lit),
430 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700431}
432
David Tolnay4a51dc72016-10-01 00:40:31 -0700433pub trait FilterAttrs<'a> {
434 type Ret: Iterator<Item = &'a Attribute>;
435
436 fn outer(self) -> Self::Ret;
437 fn inner(self) -> Self::Ret;
438}
439
David Tolnaydaaf7742016-10-03 11:11:43 -0700440impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500441where
442 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700443{
David Tolnay4a51dc72016-10-01 00:40:31 -0700444 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
445
446 fn outer(self) -> Self::Ret {
447 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700448 match attr.style {
449 AttrStyle::Outer => true,
450 _ => false,
451 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700452 }
453 self.into_iter().filter(is_outer)
454 }
455
456 fn inner(self) -> Self::Ret {
457 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700458 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700459 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700460 _ => false,
461 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700462 }
463 self.into_iter().filter(is_inner)
464 }
465}
466
David Tolnay86eca752016-09-04 11:26:41 -0700467#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700468pub mod parsing {
469 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700470
David Tolnay3a515a02018-08-25 21:08:27 -0400471 use parse::{ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700472 #[cfg(feature = "full")]
473 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700474
David Tolnayd9962eb2018-08-30 16:23:47 -0700475 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
476 let content;
477 Ok(Attribute {
478 pound_token: input.parse()?,
479 style: AttrStyle::Inner(input.parse()?),
480 bracket_token: bracketed!(content in input),
481 path: content.call(Path::parse_mod_style)?,
482 tts: content.parse()?,
483 })
David Tolnay201ef212018-01-01 00:09:14 -0500484 }
485
David Tolnayd9962eb2018-08-30 16:23:47 -0700486 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
487 let content;
488 Ok(Attribute {
489 pound_token: input.parse()?,
490 style: AttrStyle::Outer,
491 bracket_token: bracketed!(content in input),
492 path: content.call(Path::parse_mod_style)?,
493 tts: content.parse()?,
494 })
Alex Crichton954046c2017-05-30 21:49:42 -0700495 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700496
497 #[cfg(feature = "full")]
498 impl private {
499 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
500 let mut attrs = outer;
501 attrs.extend(inner);
502 attrs
503 }
504 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700505}
David Tolnay87d0b442016-09-04 11:52:12 -0700506
507#[cfg(feature = "printing")]
508mod printing {
509 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700510 use proc_macro2::TokenStream;
511 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700512
513 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700514 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700515 self.pound_token.to_tokens(tokens);
516 if let AttrStyle::Inner(ref b) = self.style {
517 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700518 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700519 self.bracket_token.surround(tokens, |tokens| {
520 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800521 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700522 });
David Tolnay87d0b442016-09-04 11:52:12 -0700523 }
524 }
525
David Tolnayaaadd782018-01-06 22:58:13 -0800526 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700527 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700528 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700529 self.paren_token.surround(tokens, |tokens| {
530 self.nested.to_tokens(tokens);
531 })
David Tolnay87d0b442016-09-04 11:52:12 -0700532 }
533 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700534
Alex Crichton62a0a592017-05-22 13:58:53 -0700535 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700536 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700537 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700538 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700539 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700540 }
541 }
David Tolnay87d0b442016-09-04 11:52:12 -0700542}