blob: 7584b702a56969ffe30bff687cf3b157dcebd70e [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
183 let mut tts = self.path.clone().into_token_stream();
184 tts.extend(self.tts.clone());
185
186 ::parse2(tts)
187 }
188
David Tolnay50660862018-09-01 15:42:53 -0700189 /// Parses zero or more outer 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_outer(input: ParseStream) -> Result<Vec<Self>> {
195 let mut attrs = Vec::new();
196 while input.peek(Token![#]) {
197 attrs.push(input.call(parsing::single_parse_outer)?);
198 }
199 Ok(attrs)
200 }
201
202 /// Parses zero or more inner attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700203 ///
204 /// *This function is available if Syn is built with the `"parsing"`
205 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700206 #[cfg(feature = "parsing")]
207 pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> {
208 let mut attrs = Vec::new();
209 while input.peek(Token![#]) && input.peek2(Token![!]) {
210 attrs.push(input.call(parsing::single_parse_inner)?);
211 }
212 Ok(attrs)
213 }
214
Alex Crichton9a4dca22018-03-28 06:32:19 -0700215 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
216 let g = match *tt {
217 TokenTree::Group(ref g) => g,
218 _ => return None,
219 };
220 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700221 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700222 }
223 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
224 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
225 Some(n) => n,
226 None => return None,
227 };
228 Some(Meta::List(MetaList {
229 paren_token: token::Paren(g.span()),
230 ident: ident,
231 nested: nested,
232 }))
233 }
234
235 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
236 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700237 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700238 _ => return None,
239 };
240 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700241 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700242 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700243 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700244 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700245 }
246
247 match *b {
248 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
249 Some(Meta::NameValue(MetaNameValue {
250 ident: ident,
251 eq_token: Token![=]([a.span()]),
252 lit: Lit::new(l.clone()),
253 }))
254 }
David Tolnaya4319b72018-06-02 00:49:15 -0700255 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700256 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
257 ident: ident,
258 eq_token: Token![=]([a.span()]),
259 lit: Lit::Bool(LitBool {
260 value: v == "true",
261 span: b.span(),
262 }),
263 })),
264 _ => None,
265 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700266 _ => None,
267 }
268 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700269}
270
David Tolnayaaadd782018-01-06 22:58:13 -0800271fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700272 assert!(!tts.is_empty());
273
Alex Crichton9a4dca22018-03-28 06:32:19 -0700274 match tts[0] {
275 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800276 if lit.to_string().starts_with('/') {
277 None
278 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700279 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800280 Some((NestedMeta::Literal(lit), &tts[1..]))
281 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700282 }
283
Alex Crichtona74a1c82018-05-16 10:20:44 -0700284 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700285 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700286 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700287 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700288 }
289 }
290
291 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700292 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700293 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700294 }
295 }
296
David Tolnay4c510042018-09-12 00:04:51 -0700297 let nested_meta = if ident == "true" || ident == "false" {
298 NestedMeta::Literal(Lit::Bool(LitBool {
299 value: ident == "true",
300 span: ident.span(),
301 }))
302 } else {
303 NestedMeta::Meta(Meta::Word(ident.clone()))
304 };
305 Some((nested_meta, &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700306 }
307
David Tolnay51382052017-12-27 13:46:21 -0500308 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700309 }
310}
311
David Tolnay51382052017-12-27 13:46:21 -0500312fn list_of_nested_meta_items_from_tokens(
313 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800314) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500315 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700316 let mut first = true;
317
318 while !tts.is_empty() {
319 let prev_comma = if first {
320 first = false;
321 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700322 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700323 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700324 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700325 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700326 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700327 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700328 }
329 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700330 tts = &tts[1..];
331 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500332 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700333 }
334 Some(tok)
335 } else {
David Tolnay51382052017-12-27 13:46:21 -0500336 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700337 };
338 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
339 Some(pair) => pair,
340 None => return None,
341 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500342 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800343 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700344 }
David Tolnay56080682018-01-06 14:01:52 -0800345 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700346 tts = rest;
347 }
348
David Tolnayf2cfd722017-12-31 18:02:51 -0500349 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700350}
351
Alex Crichton62a0a592017-05-22 13:58:53 -0700352ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800353 /// Distinguishes between attributes that decorate an item and attributes
354 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800355 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800356 /// *This type is available if Syn is built with the `"derive"` or `"full"`
357 /// feature.*
358 ///
David Tolnay23557142018-01-06 22:45:40 -0800359 /// # Outer attributes
360 ///
361 /// - `#[repr(transparent)]`
362 /// - `/// # Example`
363 /// - `/** Please file an issue */`
364 ///
365 /// # Inner attributes
366 ///
367 /// - `#![feature(proc_macro)]`
368 /// - `//! # Example`
369 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700370 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700371 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700372 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800373 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700374 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700375}
376
Alex Crichton62a0a592017-05-22 13:58:53 -0700377ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800378 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700379 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800380 /// *This type is available if Syn is built with the `"derive"` or `"full"`
381 /// feature.*
382 ///
David Tolnay068120a2018-01-06 23:17:22 -0800383 /// ## Word
384 ///
385 /// A meta word is like the `test` in `#[test]`.
386 ///
387 /// ## List
388 ///
389 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
390 ///
391 /// ## NameValue
392 ///
393 /// A name-value meta is like the `path = "..."` in `#[path =
394 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800395 ///
396 /// # Syntax tree enum
397 ///
398 /// This type is a [syntax tree enum].
399 ///
400 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800401 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800402 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800403 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800404 ///
405 /// *This type is available if Syn is built with the `"derive"` or
406 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800407 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700408 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500409 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800410 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700411 }),
David Tolnay068120a2018-01-06 23:17:22 -0800412 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800413 ///
414 /// *This type is available if Syn is built with the `"derive"` or
415 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700416 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700417 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800418 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700419 pub lit: Lit,
420 }),
421 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700422}
423
David Tolnayaaadd782018-01-06 22:58:13 -0800424impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800425 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700426 ///
David Tolnay068120a2018-01-06 23:17:22 -0800427 /// For example this would return the `test` in `#[test]`, the `derive` in
428 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
429 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700430 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700431 Meta::Word(ref meta) => meta.clone(),
432 Meta::List(ref meta) => meta.ident.clone(),
433 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700434 }
435 }
David Tolnay8e661e22016-09-27 00:00:04 -0700436}
437
Alex Crichton62a0a592017-05-22 13:58:53 -0700438ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800439 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800440 ///
441 /// *This type is available if Syn is built with the `"derive"` or `"full"`
442 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800443 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800444 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
445 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800446 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500447
David Tolnay068120a2018-01-06 23:17:22 -0800448 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700449 pub Literal(Lit),
450 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700451}
452
David Tolnay4a51dc72016-10-01 00:40:31 -0700453pub trait FilterAttrs<'a> {
454 type Ret: Iterator<Item = &'a Attribute>;
455
456 fn outer(self) -> Self::Ret;
457 fn inner(self) -> Self::Ret;
458}
459
David Tolnaydaaf7742016-10-03 11:11:43 -0700460impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500461where
462 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700463{
David Tolnay4a51dc72016-10-01 00:40:31 -0700464 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
465
466 fn outer(self) -> Self::Ret {
467 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700468 match attr.style {
469 AttrStyle::Outer => true,
470 _ => false,
471 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700472 }
473 self.into_iter().filter(is_outer)
474 }
475
476 fn inner(self) -> Self::Ret {
477 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700478 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700479 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700480 _ => false,
481 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700482 }
483 self.into_iter().filter(is_inner)
484 }
485}
486
David Tolnay86eca752016-09-04 11:26:41 -0700487#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700488pub mod parsing {
489 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700490
Carl Lerchefc96cd22018-10-12 20:45:07 -0700491 use parse::{Parse, ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700492 #[cfg(feature = "full")]
493 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700494
David Tolnayd9962eb2018-08-30 16:23:47 -0700495 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
496 let content;
497 Ok(Attribute {
498 pound_token: input.parse()?,
499 style: AttrStyle::Inner(input.parse()?),
500 bracket_token: bracketed!(content in input),
501 path: content.call(Path::parse_mod_style)?,
502 tts: content.parse()?,
503 })
David Tolnay201ef212018-01-01 00:09:14 -0500504 }
505
David Tolnayd9962eb2018-08-30 16:23:47 -0700506 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
507 let content;
508 Ok(Attribute {
509 pound_token: input.parse()?,
510 style: AttrStyle::Outer,
511 bracket_token: bracketed!(content in input),
512 path: content.call(Path::parse_mod_style)?,
513 tts: content.parse()?,
514 })
Alex Crichton954046c2017-05-30 21:49:42 -0700515 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700516
517 #[cfg(feature = "full")]
518 impl private {
519 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
520 let mut attrs = outer;
521 attrs.extend(inner);
522 attrs
523 }
524 }
Carl Lerchefc96cd22018-10-12 20:45:07 -0700525
526 impl Parse for Meta {
527 fn parse(input: ParseStream) -> Result<Self> {
528 // Detect what kind of meta this is.
529 let ahead = input.fork();
530
531 // The first token must be an identifier
532 ahead.parse::<Ident>()?;
533
534 if ahead.peek(token::Paren) {
535 Ok(Meta::List(input.parse()?))
536 } else if ahead.peek(token::Eq) {
537 Ok(Meta::NameValue(input.parse()?))
538 } else {
539 Ok(Meta::Word(input.parse()?))
540 }
541 }
542 }
543
544 impl Parse for MetaList {
545 fn parse(input: ParseStream) -> Result<Self> {
546 let ident = input.parse()?;
547
548 let content;
549 let paren_token = parenthesized!(content in input);
550 let nested = content.parse_terminated(NestedMeta::parse)?;
551
552 Ok(MetaList {
553 ident,
554 paren_token,
555 nested,
556 })
557 }
558 }
559
560 impl Parse for MetaNameValue {
561 fn parse(input: ParseStream) -> Result<Self> {
562 Ok(MetaNameValue {
563 ident: input.parse()?,
564 eq_token: input.parse()?,
565 lit: input.parse()?,
566 })
567 }
568 }
569
570 impl Parse for NestedMeta {
571 fn parse(input: ParseStream) -> Result<Self> {
572 // If it starts with an Ident then it is parsed as a `Meta` item.
573 if input.peek(Ident) {
574 Ok(NestedMeta::Meta(input.parse()?))
575 } else {
576 Ok(NestedMeta::Literal(input.parse()?))
577 }
578 }
579 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700580}
David Tolnay87d0b442016-09-04 11:52:12 -0700581
582#[cfg(feature = "printing")]
583mod printing {
584 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700585 use proc_macro2::TokenStream;
586 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700587
588 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700589 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700590 self.pound_token.to_tokens(tokens);
591 if let AttrStyle::Inner(ref b) = self.style {
592 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700593 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700594 self.bracket_token.surround(tokens, |tokens| {
595 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800596 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700597 });
David Tolnay87d0b442016-09-04 11:52:12 -0700598 }
599 }
600
David Tolnayaaadd782018-01-06 22:58:13 -0800601 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700602 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700603 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700604 self.paren_token.surround(tokens, |tokens| {
605 self.nested.to_tokens(tokens);
606 })
David Tolnay87d0b442016-09-04 11:52:12 -0700607 }
608 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700609
Alex Crichton62a0a592017-05-22 13:58:53 -0700610 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700611 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700612 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700613 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700614 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700615 }
616 }
David Tolnay87d0b442016-09-04 11:52:12 -0700617}