blob: 7ca41b0e2a4e42807b40ccbf6d127e7dc857ad2f [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
David Tolnay4c510042018-09-12 00:04:51 -0700285 let nested_meta = if ident == "true" || ident == "false" {
286 NestedMeta::Literal(Lit::Bool(LitBool {
287 value: ident == "true",
288 span: ident.span(),
289 }))
290 } else {
291 NestedMeta::Meta(Meta::Word(ident.clone()))
292 };
293 Some((nested_meta, &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700294 }
295
David Tolnay51382052017-12-27 13:46:21 -0500296 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700297 }
298}
299
David Tolnay51382052017-12-27 13:46:21 -0500300fn list_of_nested_meta_items_from_tokens(
301 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800302) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500303 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700304 let mut first = true;
305
306 while !tts.is_empty() {
307 let prev_comma = if first {
308 first = false;
309 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700310 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700311 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700312 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700313 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700314 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700315 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700316 }
317 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700318 tts = &tts[1..];
319 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500320 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700321 }
322 Some(tok)
323 } else {
David Tolnay51382052017-12-27 13:46:21 -0500324 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700325 };
326 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
327 Some(pair) => pair,
328 None => return None,
329 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500330 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800331 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700332 }
David Tolnay56080682018-01-06 14:01:52 -0800333 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700334 tts = rest;
335 }
336
David Tolnayf2cfd722017-12-31 18:02:51 -0500337 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700338}
339
Alex Crichton62a0a592017-05-22 13:58:53 -0700340ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800341 /// Distinguishes between attributes that decorate an item and attributes
342 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800343 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800344 /// *This type is available if Syn is built with the `"derive"` or `"full"`
345 /// feature.*
346 ///
David Tolnay23557142018-01-06 22:45:40 -0800347 /// # Outer attributes
348 ///
349 /// - `#[repr(transparent)]`
350 /// - `/// # Example`
351 /// - `/** Please file an issue */`
352 ///
353 /// # Inner attributes
354 ///
355 /// - `#![feature(proc_macro)]`
356 /// - `//! # Example`
357 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700358 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700359 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700360 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800361 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700362 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700363}
364
Alex Crichton62a0a592017-05-22 13:58:53 -0700365ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800366 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700367 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800368 /// *This type is available if Syn is built with the `"derive"` or `"full"`
369 /// feature.*
370 ///
David Tolnay068120a2018-01-06 23:17:22 -0800371 /// ## Word
372 ///
373 /// A meta word is like the `test` in `#[test]`.
374 ///
375 /// ## List
376 ///
377 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
378 ///
379 /// ## NameValue
380 ///
381 /// A name-value meta is like the `path = "..."` in `#[path =
382 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800383 ///
384 /// # Syntax tree enum
385 ///
386 /// This type is a [syntax tree enum].
387 ///
388 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800389 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800390 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800391 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800392 ///
393 /// *This type is available if Syn is built with the `"derive"` or
394 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800395 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700396 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500397 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800398 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700399 }),
David Tolnay068120a2018-01-06 23:17:22 -0800400 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800401 ///
402 /// *This type is available if Syn is built with the `"derive"` or
403 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700404 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700405 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800406 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700407 pub lit: Lit,
408 }),
409 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700410}
411
David Tolnayaaadd782018-01-06 22:58:13 -0800412impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800413 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700414 ///
David Tolnay068120a2018-01-06 23:17:22 -0800415 /// For example this would return the `test` in `#[test]`, the `derive` in
416 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
417 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700418 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700419 Meta::Word(ref meta) => meta.clone(),
420 Meta::List(ref meta) => meta.ident.clone(),
421 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700422 }
423 }
David Tolnay8e661e22016-09-27 00:00:04 -0700424}
425
Alex Crichton62a0a592017-05-22 13:58:53 -0700426ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800427 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800428 ///
429 /// *This type is available if Syn is built with the `"derive"` or `"full"`
430 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800431 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800432 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
433 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800434 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500435
David Tolnay068120a2018-01-06 23:17:22 -0800436 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700437 pub Literal(Lit),
438 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700439}
440
David Tolnay4a51dc72016-10-01 00:40:31 -0700441pub trait FilterAttrs<'a> {
442 type Ret: Iterator<Item = &'a Attribute>;
443
444 fn outer(self) -> Self::Ret;
445 fn inner(self) -> Self::Ret;
446}
447
David Tolnaydaaf7742016-10-03 11:11:43 -0700448impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500449where
450 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700451{
David Tolnay4a51dc72016-10-01 00:40:31 -0700452 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
453
454 fn outer(self) -> Self::Ret {
455 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700456 match attr.style {
457 AttrStyle::Outer => true,
458 _ => false,
459 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700460 }
461 self.into_iter().filter(is_outer)
462 }
463
464 fn inner(self) -> Self::Ret {
465 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700466 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700467 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700468 _ => false,
469 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700470 }
471 self.into_iter().filter(is_inner)
472 }
473}
474
David Tolnay86eca752016-09-04 11:26:41 -0700475#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700476pub mod parsing {
477 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700478
Carl Lerchefc96cd22018-10-12 20:45:07 -0700479 use parse::{Parse, ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700480 #[cfg(feature = "full")]
481 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700482
David Tolnayd9962eb2018-08-30 16:23:47 -0700483 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
484 let content;
485 Ok(Attribute {
486 pound_token: input.parse()?,
487 style: AttrStyle::Inner(input.parse()?),
488 bracket_token: bracketed!(content in input),
489 path: content.call(Path::parse_mod_style)?,
490 tts: content.parse()?,
491 })
David Tolnay201ef212018-01-01 00:09:14 -0500492 }
493
David Tolnayd9962eb2018-08-30 16:23:47 -0700494 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
495 let content;
496 Ok(Attribute {
497 pound_token: input.parse()?,
498 style: AttrStyle::Outer,
499 bracket_token: bracketed!(content in input),
500 path: content.call(Path::parse_mod_style)?,
501 tts: content.parse()?,
502 })
Alex Crichton954046c2017-05-30 21:49:42 -0700503 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700504
505 #[cfg(feature = "full")]
506 impl private {
507 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
508 let mut attrs = outer;
509 attrs.extend(inner);
510 attrs
511 }
512 }
Carl Lerchefc96cd22018-10-12 20:45:07 -0700513
514 impl Parse for Meta {
515 fn parse(input: ParseStream) -> Result<Self> {
516 // Detect what kind of meta this is.
517 let ahead = input.fork();
518
519 // The first token must be an identifier
520 ahead.parse::<Ident>()?;
521
522 if ahead.peek(token::Paren) {
523 Ok(Meta::List(input.parse()?))
524 } else if ahead.peek(token::Eq) {
525 Ok(Meta::NameValue(input.parse()?))
526 } else {
527 Ok(Meta::Word(input.parse()?))
528 }
529 }
530 }
531
532 impl Parse for MetaList {
533 fn parse(input: ParseStream) -> Result<Self> {
534 let ident = input.parse()?;
535
536 let content;
537 let paren_token = parenthesized!(content in input);
538 let nested = content.parse_terminated(NestedMeta::parse)?;
539
540 Ok(MetaList {
541 ident,
542 paren_token,
543 nested,
544 })
545 }
546 }
547
548 impl Parse for MetaNameValue {
549 fn parse(input: ParseStream) -> Result<Self> {
550 Ok(MetaNameValue {
551 ident: input.parse()?,
552 eq_token: input.parse()?,
553 lit: input.parse()?,
554 })
555 }
556 }
557
558 impl Parse for NestedMeta {
559 fn parse(input: ParseStream) -> Result<Self> {
560 // If it starts with an Ident then it is parsed as a `Meta` item.
561 if input.peek(Ident) {
562 Ok(NestedMeta::Meta(input.parse()?))
563 } else {
564 Ok(NestedMeta::Literal(input.parse()?))
565 }
566 }
567 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700568}
David Tolnay87d0b442016-09-04 11:52:12 -0700569
570#[cfg(feature = "printing")]
571mod printing {
572 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700573 use proc_macro2::TokenStream;
574 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700575
576 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700577 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700578 self.pound_token.to_tokens(tokens);
579 if let AttrStyle::Inner(ref b) = self.style {
580 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700581 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700582 self.bracket_token.surround(tokens, |tokens| {
583 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800584 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700585 });
David Tolnay87d0b442016-09-04 11:52:12 -0700586 }
587 }
588
David Tolnayaaadd782018-01-06 22:58:13 -0800589 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700590 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700591 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700592 self.paren_token.surround(tokens, |tokens| {
593 self.nested.to_tokens(tokens);
594 })
David Tolnay87d0b442016-09-04 11:52:12 -0700595 }
596 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700597
Alex Crichton62a0a592017-05-22 13:58:53 -0700598 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700599 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700600 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700601 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700602 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700603 }
604 }
David Tolnay87d0b442016-09-04 11:52:12 -0700605}