blob: 3bf12409ce200e3cc3ac5fd542272e02bc2e3bf4 [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
Carl Lercheae0fa602018-10-12 21:46:54 -0700177 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
178 /// possible.
179 #[cfg(feature = "parsing")]
180 pub fn parse_meta(&self) -> Result<Meta> {
181 use quote::ToTokens;
182
Carl Lerche22926d72018-10-12 22:29:11 -0700183 let mut tts = TokenStream::new();
184
185 self.path.to_tokens(&mut tts);
186 self.tts.to_tokens(&mut tts);
Carl Lercheae0fa602018-10-12 21:46:54 -0700187
188 ::parse2(tts)
189 }
190
David Tolnay50660862018-09-01 15:42:53 -0700191 /// Parses zero or more outer attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700192 ///
193 /// *This function is available if Syn is built with the `"parsing"`
194 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700195 #[cfg(feature = "parsing")]
196 pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> {
197 let mut attrs = Vec::new();
198 while input.peek(Token![#]) {
199 attrs.push(input.call(parsing::single_parse_outer)?);
200 }
201 Ok(attrs)
202 }
203
204 /// Parses zero or more inner attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700205 ///
206 /// *This function is available if Syn is built with the `"parsing"`
207 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700208 #[cfg(feature = "parsing")]
209 pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> {
210 let mut attrs = Vec::new();
211 while input.peek(Token![#]) && input.peek2(Token![!]) {
212 attrs.push(input.call(parsing::single_parse_inner)?);
213 }
214 Ok(attrs)
215 }
216
Alex Crichton9a4dca22018-03-28 06:32:19 -0700217 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
218 let g = match *tt {
219 TokenTree::Group(ref g) => g,
220 _ => return None,
221 };
222 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700223 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700224 }
225 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
226 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
227 Some(n) => n,
228 None => return None,
229 };
230 Some(Meta::List(MetaList {
231 paren_token: token::Paren(g.span()),
232 ident: ident,
233 nested: nested,
234 }))
235 }
236
237 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
238 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700239 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700240 _ => return None,
241 };
242 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700243 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700244 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700245 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700246 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700247 }
248
249 match *b {
250 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
251 Some(Meta::NameValue(MetaNameValue {
252 ident: ident,
253 eq_token: Token![=]([a.span()]),
254 lit: Lit::new(l.clone()),
255 }))
256 }
David Tolnaya4319b72018-06-02 00:49:15 -0700257 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700258 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
259 ident: ident,
260 eq_token: Token![=]([a.span()]),
261 lit: Lit::Bool(LitBool {
262 value: v == "true",
263 span: b.span(),
264 }),
265 })),
266 _ => None,
267 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700268 _ => None,
269 }
270 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700271}
272
David Tolnayaaadd782018-01-06 22:58:13 -0800273fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700274 assert!(!tts.is_empty());
275
Alex Crichton9a4dca22018-03-28 06:32:19 -0700276 match tts[0] {
277 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800278 if lit.to_string().starts_with('/') {
279 None
280 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700281 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800282 Some((NestedMeta::Literal(lit), &tts[1..]))
283 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700284 }
285
Alex Crichtona74a1c82018-05-16 10:20:44 -0700286 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700287 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700288 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700289 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700290 }
291 }
292
293 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700294 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700295 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700296 }
297 }
298
David Tolnay4c510042018-09-12 00:04:51 -0700299 let nested_meta = if ident == "true" || ident == "false" {
300 NestedMeta::Literal(Lit::Bool(LitBool {
301 value: ident == "true",
302 span: ident.span(),
303 }))
304 } else {
305 NestedMeta::Meta(Meta::Word(ident.clone()))
306 };
307 Some((nested_meta, &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700308 }
309
David Tolnay51382052017-12-27 13:46:21 -0500310 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700311 }
312}
313
David Tolnay51382052017-12-27 13:46:21 -0500314fn list_of_nested_meta_items_from_tokens(
315 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800316) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500317 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700318 let mut first = true;
319
320 while !tts.is_empty() {
321 let prev_comma = if first {
322 first = false;
323 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700324 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700325 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700326 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700327 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700328 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700329 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700330 }
331 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700332 tts = &tts[1..];
333 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500334 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700335 }
336 Some(tok)
337 } else {
David Tolnay51382052017-12-27 13:46:21 -0500338 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700339 };
340 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
341 Some(pair) => pair,
342 None => return None,
343 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500344 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800345 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700346 }
David Tolnay56080682018-01-06 14:01:52 -0800347 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700348 tts = rest;
349 }
350
David Tolnayf2cfd722017-12-31 18:02:51 -0500351 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700352}
353
Alex Crichton62a0a592017-05-22 13:58:53 -0700354ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800355 /// Distinguishes between attributes that decorate an item and attributes
356 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800357 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800358 /// *This type is available if Syn is built with the `"derive"` or `"full"`
359 /// feature.*
360 ///
David Tolnay23557142018-01-06 22:45:40 -0800361 /// # Outer attributes
362 ///
363 /// - `#[repr(transparent)]`
364 /// - `/// # Example`
365 /// - `/** Please file an issue */`
366 ///
367 /// # Inner attributes
368 ///
369 /// - `#![feature(proc_macro)]`
370 /// - `//! # Example`
371 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700372 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700373 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700374 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800375 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700376 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700377}
378
Alex Crichton62a0a592017-05-22 13:58:53 -0700379ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800380 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700381 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800382 /// *This type is available if Syn is built with the `"derive"` or `"full"`
383 /// feature.*
384 ///
David Tolnay068120a2018-01-06 23:17:22 -0800385 /// ## Word
386 ///
387 /// A meta word is like the `test` in `#[test]`.
388 ///
389 /// ## List
390 ///
391 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
392 ///
393 /// ## NameValue
394 ///
395 /// A name-value meta is like the `path = "..."` in `#[path =
396 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800397 ///
398 /// # Syntax tree enum
399 ///
400 /// This type is a [syntax tree enum].
401 ///
402 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800403 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800404 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800405 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800406 ///
407 /// *This type is available if Syn is built with the `"derive"` or
408 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800409 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700410 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500411 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800412 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700413 }),
David Tolnay068120a2018-01-06 23:17:22 -0800414 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800415 ///
416 /// *This type is available if Syn is built with the `"derive"` or
417 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700418 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700419 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800420 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700421 pub lit: Lit,
422 }),
423 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700424}
425
David Tolnayaaadd782018-01-06 22:58:13 -0800426impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800427 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700428 ///
David Tolnay068120a2018-01-06 23:17:22 -0800429 /// For example this would return the `test` in `#[test]`, the `derive` in
430 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
431 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700432 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700433 Meta::Word(ref meta) => meta.clone(),
434 Meta::List(ref meta) => meta.ident.clone(),
435 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700436 }
437 }
David Tolnay8e661e22016-09-27 00:00:04 -0700438}
439
Alex Crichton62a0a592017-05-22 13:58:53 -0700440ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800441 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800442 ///
443 /// *This type is available if Syn is built with the `"derive"` or `"full"`
444 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800445 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800446 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
447 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800448 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500449
David Tolnay068120a2018-01-06 23:17:22 -0800450 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700451 pub Literal(Lit),
452 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700453}
454
David Tolnay4a51dc72016-10-01 00:40:31 -0700455pub trait FilterAttrs<'a> {
456 type Ret: Iterator<Item = &'a Attribute>;
457
458 fn outer(self) -> Self::Ret;
459 fn inner(self) -> Self::Ret;
460}
461
David Tolnaydaaf7742016-10-03 11:11:43 -0700462impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500463where
464 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700465{
David Tolnay4a51dc72016-10-01 00:40:31 -0700466 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
467
468 fn outer(self) -> Self::Ret {
469 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700470 match attr.style {
471 AttrStyle::Outer => true,
472 _ => false,
473 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700474 }
475 self.into_iter().filter(is_outer)
476 }
477
478 fn inner(self) -> Self::Ret {
479 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700480 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700481 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700482 _ => false,
483 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700484 }
485 self.into_iter().filter(is_inner)
486 }
487}
488
David Tolnay86eca752016-09-04 11:26:41 -0700489#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700490pub mod parsing {
491 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700492
Carl Lerchefc96cd22018-10-12 20:45:07 -0700493 use parse::{Parse, ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700494 #[cfg(feature = "full")]
495 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700496
David Tolnayd9962eb2018-08-30 16:23:47 -0700497 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
498 let content;
499 Ok(Attribute {
500 pound_token: input.parse()?,
501 style: AttrStyle::Inner(input.parse()?),
502 bracket_token: bracketed!(content in input),
503 path: content.call(Path::parse_mod_style)?,
504 tts: content.parse()?,
505 })
David Tolnay201ef212018-01-01 00:09:14 -0500506 }
507
David Tolnayd9962eb2018-08-30 16:23:47 -0700508 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
509 let content;
510 Ok(Attribute {
511 pound_token: input.parse()?,
512 style: AttrStyle::Outer,
513 bracket_token: bracketed!(content in input),
514 path: content.call(Path::parse_mod_style)?,
515 tts: content.parse()?,
516 })
Alex Crichton954046c2017-05-30 21:49:42 -0700517 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700518
519 #[cfg(feature = "full")]
520 impl private {
521 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
522 let mut attrs = outer;
523 attrs.extend(inner);
524 attrs
525 }
526 }
Carl Lerchefc96cd22018-10-12 20:45:07 -0700527
528 impl Parse for Meta {
529 fn parse(input: ParseStream) -> Result<Self> {
530 // Detect what kind of meta this is.
531 let ahead = input.fork();
532
533 // The first token must be an identifier
534 ahead.parse::<Ident>()?;
535
536 if ahead.peek(token::Paren) {
537 Ok(Meta::List(input.parse()?))
538 } else if ahead.peek(token::Eq) {
539 Ok(Meta::NameValue(input.parse()?))
540 } else {
541 Ok(Meta::Word(input.parse()?))
542 }
543 }
544 }
545
546 impl Parse for MetaList {
547 fn parse(input: ParseStream) -> Result<Self> {
548 let ident = input.parse()?;
549
550 let content;
551 let paren_token = parenthesized!(content in input);
552 let nested = content.parse_terminated(NestedMeta::parse)?;
553
554 Ok(MetaList {
Carl Lerche7ef37f32018-10-12 21:59:46 -0700555 ident: ident,
556 paren_token: paren_token,
557 nested: nested,
Carl Lerchefc96cd22018-10-12 20:45:07 -0700558 })
559 }
560 }
561
562 impl Parse for MetaNameValue {
563 fn parse(input: ParseStream) -> Result<Self> {
564 Ok(MetaNameValue {
565 ident: input.parse()?,
566 eq_token: input.parse()?,
567 lit: input.parse()?,
568 })
569 }
570 }
571
572 impl Parse for NestedMeta {
573 fn parse(input: ParseStream) -> Result<Self> {
574 // If it starts with an Ident then it is parsed as a `Meta` item.
575 if input.peek(Ident) {
576 Ok(NestedMeta::Meta(input.parse()?))
577 } else {
578 Ok(NestedMeta::Literal(input.parse()?))
579 }
580 }
581 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700582}
David Tolnay87d0b442016-09-04 11:52:12 -0700583
584#[cfg(feature = "printing")]
585mod printing {
586 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700587 use proc_macro2::TokenStream;
588 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700589
590 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700591 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700592 self.pound_token.to_tokens(tokens);
593 if let AttrStyle::Inner(ref b) = self.style {
594 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700595 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700596 self.bracket_token.surround(tokens, |tokens| {
597 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800598 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700599 });
David Tolnay87d0b442016-09-04 11:52:12 -0700600 }
601 }
602
David Tolnayaaadd782018-01-06 22:58:13 -0800603 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700604 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700605 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700606 self.paren_token.surround(tokens, |tokens| {
607 self.nested.to_tokens(tokens);
608 })
David Tolnay87d0b442016-09-04 11:52:12 -0700609 }
610 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700611
Alex Crichton62a0a592017-05-22 13:58:53 -0700612 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700613 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700614 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700615 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700616 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700617 }
618 }
David Tolnay87d0b442016-09-04 11:52:12 -0700619}