blob: 595f12a10be753c24873adf79b18c1d029a5ae8d [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 /// ```
79 /// # extern crate syn;
80 /// #
81 /// use syn::{Attribute, Ident, Token};
82 /// use syn::parse::{Parse, ParseStream, Result};
83 ///
84 /// // Parses a unit struct with attributes.
85 /// //
86 /// // #[path = "s.tmpl"]
87 /// // struct S;
88 /// struct UnitStruct {
89 /// attrs: Vec<Attribute>,
90 /// struct_token: Token![struct],
91 /// name: Ident,
92 /// semi_token: Token![;],
93 /// }
94 ///
95 /// impl Parse for UnitStruct {
96 /// fn parse(input: ParseStream) -> Result<Self> {
97 /// Ok(UnitStruct {
98 /// attrs: input.call(Attribute::parse_outer)?,
99 /// struct_token: input.parse()?,
100 /// name: input.parse()?,
101 /// semi_token: input.parse()?,
102 /// })
103 /// }
104 /// }
105 /// #
106 /// # fn main() {}
107 /// ```
David Tolnay9c76bcb2017-12-26 23:14:59 -0500108 pub struct Attribute #manual_extra_traits {
David Tolnayf8db7ba2017-11-11 22:52:16 -0800109 pub pound_token: Token![#],
David Tolnay4a3f59a2017-12-28 21:21:12 -0500110 pub style: AttrStyle,
David Tolnay32954ef2017-12-26 22:43:16 -0500111 pub bracket_token: token::Bracket,
Alex Crichton62a0a592017-05-22 13:58:53 -0700112 pub path: Path,
David Tolnay369f0c52017-12-27 01:50:45 -0500113 pub tts: TokenStream,
Alex Crichton62a0a592017-05-22 13:58:53 -0700114 }
David Tolnayb79ee962016-09-04 09:39:20 -0700115}
116
David Tolnay9c76bcb2017-12-26 23:14:59 -0500117#[cfg(feature = "extra-traits")]
118impl Eq for Attribute {}
119
120#[cfg(feature = "extra-traits")]
121impl PartialEq for Attribute {
122 fn eq(&self, other: &Self) -> bool {
David Tolnay65fb5662018-05-20 20:02:28 -0700123 self.style == other.style
124 && self.pound_token == other.pound_token
125 && self.bracket_token == other.bracket_token
126 && self.path == other.path
David Tolnay369f0c52017-12-27 01:50:45 -0500127 && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts)
David Tolnay9c76bcb2017-12-26 23:14:59 -0500128 }
129}
130
131#[cfg(feature = "extra-traits")]
132impl Hash for Attribute {
133 fn hash<H>(&self, state: &mut H)
David Tolnay51382052017-12-27 13:46:21 -0500134 where
135 H: Hasher,
David Tolnay9c76bcb2017-12-26 23:14:59 -0500136 {
137 self.style.hash(state);
138 self.pound_token.hash(state);
139 self.bracket_token.hash(state);
140 self.path.hash(state);
David Tolnay369f0c52017-12-27 01:50:45 -0500141 TokenStreamHelper(&self.tts).hash(state);
David Tolnay9c76bcb2017-12-26 23:14:59 -0500142 }
143}
144
David Tolnay02d77cc2016-10-02 09:52:08 -0700145impl Attribute {
David Tolnay068120a2018-01-06 23:17:22 -0800146 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
147 /// possible.
David Tolnayaaadd782018-01-06 22:58:13 -0800148 pub fn interpret_meta(&self) -> Option<Meta> {
Arnavion95f8a7a2017-04-19 03:29:56 -0700149 let name = if self.path.segments.len() == 1 {
David Tolnay56080682018-01-06 14:01:52 -0800150 &self.path.segments.first().unwrap().value().ident
Arnavion95f8a7a2017-04-19 03:29:56 -0700151 } else {
152 return None;
153 };
154
Arnavionbf395bf2017-04-15 15:35:22 -0700155 if self.tts.is_empty() {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700156 return Some(Meta::Word(name.clone()));
Arnavionbf395bf2017-04-15 15:35:22 -0700157 }
158
David Tolnay369f0c52017-12-27 01:50:45 -0500159 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
160
161 if tts.len() == 1 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700162 if let Some(meta) = Attribute::extract_meta_list(name.clone(), &tts[0]) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700163 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700164 }
165 }
166
David Tolnay369f0c52017-12-27 01:50:45 -0500167 if tts.len() == 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700168 if let Some(meta) = Attribute::extract_name_value(name.clone(), &tts[0], &tts[1]) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700169 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700170 }
171 }
172
173 None
David Tolnay02d77cc2016-10-02 09:52:08 -0700174 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700175
David Tolnay50660862018-09-01 15:42:53 -0700176 /// Parses zero or more outer attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700177 ///
178 /// *This function is available if Syn is built with the `"parsing"`
179 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700180 #[cfg(feature = "parsing")]
181 pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> {
182 let mut attrs = Vec::new();
183 while input.peek(Token![#]) {
184 attrs.push(input.call(parsing::single_parse_outer)?);
185 }
186 Ok(attrs)
187 }
188
189 /// Parses zero or more inner attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700190 ///
191 /// *This function is available if Syn is built with the `"parsing"`
192 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700193 #[cfg(feature = "parsing")]
194 pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> {
195 let mut attrs = Vec::new();
196 while input.peek(Token![#]) && input.peek2(Token![!]) {
197 attrs.push(input.call(parsing::single_parse_inner)?);
198 }
199 Ok(attrs)
200 }
201
Alex Crichton9a4dca22018-03-28 06:32:19 -0700202 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
203 let g = match *tt {
204 TokenTree::Group(ref g) => g,
205 _ => return None,
206 };
207 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700208 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700209 }
210 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
211 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
212 Some(n) => n,
213 None => return None,
214 };
215 Some(Meta::List(MetaList {
216 paren_token: token::Paren(g.span()),
217 ident: ident,
218 nested: nested,
219 }))
220 }
221
222 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
223 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700224 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700225 _ => return None,
226 };
227 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700228 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700229 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700230 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700231 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700232 }
233
234 match *b {
235 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
236 Some(Meta::NameValue(MetaNameValue {
237 ident: ident,
238 eq_token: Token![=]([a.span()]),
239 lit: Lit::new(l.clone()),
240 }))
241 }
David Tolnaya4319b72018-06-02 00:49:15 -0700242 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700243 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
244 ident: ident,
245 eq_token: Token![=]([a.span()]),
246 lit: Lit::Bool(LitBool {
247 value: v == "true",
248 span: b.span(),
249 }),
250 })),
251 _ => None,
252 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700253 _ => None,
254 }
255 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700256}
257
David Tolnayaaadd782018-01-06 22:58:13 -0800258fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700259 assert!(!tts.is_empty());
260
Alex Crichton9a4dca22018-03-28 06:32:19 -0700261 match tts[0] {
262 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800263 if lit.to_string().starts_with('/') {
264 None
265 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700266 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800267 Some((NestedMeta::Literal(lit), &tts[1..]))
268 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700269 }
270
Alex Crichtona74a1c82018-05-16 10:20:44 -0700271 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700272 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700273 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700274 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700275 }
276 }
277
278 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700279 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700280 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700281 }
282 }
283
Alex Crichtona74a1c82018-05-16 10:20:44 -0700284 Some((Meta::Word(ident.clone()).into(), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700285 }
286
David Tolnay51382052017-12-27 13:46:21 -0500287 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700288 }
289}
290
David Tolnay51382052017-12-27 13:46:21 -0500291fn list_of_nested_meta_items_from_tokens(
292 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800293) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500294 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700295 let mut first = true;
296
297 while !tts.is_empty() {
298 let prev_comma = if first {
299 first = false;
300 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700301 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700302 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700303 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700304 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700305 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700306 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700307 }
308 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700309 tts = &tts[1..];
310 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500311 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700312 }
313 Some(tok)
314 } else {
David Tolnay51382052017-12-27 13:46:21 -0500315 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700316 };
317 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
318 Some(pair) => pair,
319 None => return None,
320 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500321 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800322 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700323 }
David Tolnay56080682018-01-06 14:01:52 -0800324 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700325 tts = rest;
326 }
327
David Tolnayf2cfd722017-12-31 18:02:51 -0500328 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700329}
330
Alex Crichton62a0a592017-05-22 13:58:53 -0700331ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800332 /// Distinguishes between attributes that decorate an item and attributes
333 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800334 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800335 /// *This type is available if Syn is built with the `"derive"` or `"full"`
336 /// feature.*
337 ///
David Tolnay23557142018-01-06 22:45:40 -0800338 /// # Outer attributes
339 ///
340 /// - `#[repr(transparent)]`
341 /// - `/// # Example`
342 /// - `/** Please file an issue */`
343 ///
344 /// # Inner attributes
345 ///
346 /// - `#![feature(proc_macro)]`
347 /// - `//! # Example`
348 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700349 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700350 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700351 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800352 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700353 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700354}
355
Alex Crichton62a0a592017-05-22 13:58:53 -0700356ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800357 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700358 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800359 /// *This type is available if Syn is built with the `"derive"` or `"full"`
360 /// feature.*
361 ///
David Tolnay068120a2018-01-06 23:17:22 -0800362 /// ## Word
363 ///
364 /// A meta word is like the `test` in `#[test]`.
365 ///
366 /// ## List
367 ///
368 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
369 ///
370 /// ## NameValue
371 ///
372 /// A name-value meta is like the `path = "..."` in `#[path =
373 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800374 ///
375 /// # Syntax tree enum
376 ///
377 /// This type is a [syntax tree enum].
378 ///
379 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800380 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800381 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800382 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800383 ///
384 /// *This type is available if Syn is built with the `"derive"` or
385 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800386 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700387 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500388 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800389 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700390 }),
David Tolnay068120a2018-01-06 23:17:22 -0800391 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800392 ///
393 /// *This type is available if Syn is built with the `"derive"` or
394 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700395 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700396 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800397 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700398 pub lit: Lit,
399 }),
400 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700401}
402
David Tolnayaaadd782018-01-06 22:58:13 -0800403impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800404 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700405 ///
David Tolnay068120a2018-01-06 23:17:22 -0800406 /// For example this would return the `test` in `#[test]`, the `derive` in
407 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
408 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700409 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700410 Meta::Word(ref meta) => meta.clone(),
411 Meta::List(ref meta) => meta.ident.clone(),
412 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700413 }
414 }
David Tolnay8e661e22016-09-27 00:00:04 -0700415}
416
Alex Crichton62a0a592017-05-22 13:58:53 -0700417ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800418 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800419 ///
420 /// *This type is available if Syn is built with the `"derive"` or `"full"`
421 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800422 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800423 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
424 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800425 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500426
David Tolnay068120a2018-01-06 23:17:22 -0800427 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700428 pub Literal(Lit),
429 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700430}
431
David Tolnay4a51dc72016-10-01 00:40:31 -0700432pub trait FilterAttrs<'a> {
433 type Ret: Iterator<Item = &'a Attribute>;
434
435 fn outer(self) -> Self::Ret;
436 fn inner(self) -> Self::Ret;
437}
438
David Tolnaydaaf7742016-10-03 11:11:43 -0700439impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500440where
441 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700442{
David Tolnay4a51dc72016-10-01 00:40:31 -0700443 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
444
445 fn outer(self) -> Self::Ret {
446 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700447 match attr.style {
448 AttrStyle::Outer => true,
449 _ => false,
450 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700451 }
452 self.into_iter().filter(is_outer)
453 }
454
455 fn inner(self) -> Self::Ret {
456 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700457 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700458 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700459 _ => false,
460 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700461 }
462 self.into_iter().filter(is_inner)
463 }
464}
465
David Tolnay86eca752016-09-04 11:26:41 -0700466#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700467pub mod parsing {
468 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700469
David Tolnay3a515a02018-08-25 21:08:27 -0400470 use parse::{ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700471 #[cfg(feature = "full")]
472 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700473
David Tolnayd9962eb2018-08-30 16:23:47 -0700474 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
475 let content;
476 Ok(Attribute {
477 pound_token: input.parse()?,
478 style: AttrStyle::Inner(input.parse()?),
479 bracket_token: bracketed!(content in input),
480 path: content.call(Path::parse_mod_style)?,
481 tts: content.parse()?,
482 })
David Tolnay201ef212018-01-01 00:09:14 -0500483 }
484
David Tolnayd9962eb2018-08-30 16:23:47 -0700485 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
486 let content;
487 Ok(Attribute {
488 pound_token: input.parse()?,
489 style: AttrStyle::Outer,
490 bracket_token: bracketed!(content in input),
491 path: content.call(Path::parse_mod_style)?,
492 tts: content.parse()?,
493 })
Alex Crichton954046c2017-05-30 21:49:42 -0700494 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700495
496 #[cfg(feature = "full")]
497 impl private {
498 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
499 let mut attrs = outer;
500 attrs.extend(inner);
501 attrs
502 }
503 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700504}
David Tolnay87d0b442016-09-04 11:52:12 -0700505
506#[cfg(feature = "printing")]
507mod printing {
508 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700509 use proc_macro2::TokenStream;
510 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700511
512 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700513 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700514 self.pound_token.to_tokens(tokens);
515 if let AttrStyle::Inner(ref b) = self.style {
516 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700517 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700518 self.bracket_token.surround(tokens, |tokens| {
519 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800520 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700521 });
David Tolnay87d0b442016-09-04 11:52:12 -0700522 }
523 }
524
David Tolnayaaadd782018-01-06 22:58:13 -0800525 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700526 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700527 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700528 self.paren_token.surround(tokens, |tokens| {
529 self.nested.to_tokens(tokens);
530 })
David Tolnay87d0b442016-09-04 11:52:12 -0700531 }
532 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700533
Alex Crichton62a0a592017-05-22 13:58:53 -0700534 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700535 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700536 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700537 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700538 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700539 }
540 }
David Tolnay87d0b442016-09-04 11:52:12 -0700541}