blob: d1e7dca7c0e400857dd9a8d9b582f606563211d1 [file] [log] [blame]
David Tolnayb79ee962016-09-04 09:39:20 -07001use super::*;
David Tolnayf2cfd722017-12-31 18:02:51 -05002use punctuated::Punctuated;
David Tolnayb79ee962016-09-04 09:39:20 -07003
David Tolnay4a51dc72016-10-01 00:40:31 -07004use std::iter;
5
David Tolnayf1a10262018-10-13 15:33:50 -07006use proc_macro2::TokenStream;
David Tolnayf2b744b2018-10-13 14:24:01 -07007#[cfg(not(feature = "parsing"))]
8use proc_macro2::{Delimiter, Spacing, TokenTree};
David Tolnay9c76bcb2017-12-26 23:14:59 -05009
David Tolnay50660862018-09-01 15:42:53 -070010#[cfg(feature = "parsing")]
11use parse::{ParseStream, Result};
David Tolnay9c76bcb2017-12-26 23:14:59 -050012#[cfg(feature = "extra-traits")]
13use std::hash::{Hash, Hasher};
14#[cfg(feature = "extra-traits")]
David Tolnayc43b44e2017-12-30 23:55:54 -050015use tt::TokenStreamHelper;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070016
Alex Crichton62a0a592017-05-22 13:58:53 -070017ast_struct! {
David Tolnay23557142018-01-06 22:45:40 -080018 /// An attribute like `#[repr(transparent)]`.
19 ///
David Tolnay461d98e2018-01-07 11:07:19 -080020 /// *This type is available if Syn is built with the `"derive"` or `"full"`
21 /// feature.*
22 ///
David Tolnay23557142018-01-06 22:45:40 -080023 /// # Syntax
24 ///
25 /// Rust has six types of attributes.
26 ///
27 /// - Outer attributes like `#[repr(transparent)]`. These appear outside or
28 /// in front of the item they describe.
29 /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
30 /// of the item they describe, usually a module.
31 /// - Outer doc comments like `/// # Example`.
32 /// - Inner doc comments like `//! Please file an issue`.
33 /// - Outer block comments `/** # Example */`.
34 /// - Inner block comments `/*! Please file an issue */`.
35 ///
36 /// The `style` field of type `AttrStyle` distinguishes whether an attribute
37 /// is outer or inner. Doc comments and block comments are promoted to
David Tolnayfe583302018-08-24 16:09:34 -040038 /// attributes, as this is how they are processed by the compiler and by
39 /// `macro_rules!` macros.
David Tolnay23557142018-01-06 22:45:40 -080040 ///
41 /// The `path` field gives the possibly colon-delimited path against which
42 /// the attribute is resolved. It is equal to `"doc"` for desugared doc
43 /// comments. The `tts` field contains the rest of the attribute body as
44 /// tokens.
45 ///
46 /// ```text
47 /// #[derive(Copy)] #[crate::precondition x < 5]
48 /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~
49 /// path tts path tts
50 /// ```
51 ///
David Tolnay4ac734f2018-11-10 14:19:00 -080052 /// Use the [`parse_meta`] method to try parsing the tokens of an attribute
53 /// into the structured representation that is used by convention across
54 /// most Rust libraries.
David Tolnay23557142018-01-06 22:45:40 -080055 ///
Andy Russellce34d592018-11-10 12:10:39 -050056 /// [`parse_meta`]: #method.parse_meta
David Tolnayd8bd15f2018-09-01 16:57:39 -070057 ///
58 /// # Parsing
59 ///
60 /// This type does not implement the [`Parse`] trait and thus cannot be
61 /// parsed directly by [`ParseStream::parse`]. Instead use
62 /// [`ParseStream::call`] with one of the two parser functions
63 /// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
64 /// which you intend to parse.
65 ///
66 /// [`Parse`]: parse/trait.Parse.html
67 /// [`ParseStream::parse`]: parse/struct.ParseBuffer.html#method.parse
68 /// [`ParseStream::call`]: parse/struct.ParseBuffer.html#method.call
69 /// [`Attribute::parse_outer`]: #method.parse_outer
70 /// [`Attribute::parse_inner`]: #method.parse_inner
71 ///
David Tolnay95989db2019-01-01 15:05:57 -050072 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -050073 /// use syn::{Attribute, Ident, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -080074 /// use syn::parse::{Parse, ParseStream};
David Tolnayd8bd15f2018-09-01 16:57:39 -070075 ///
76 /// // Parses a unit struct with attributes.
77 /// //
78 /// // #[path = "s.tmpl"]
79 /// // struct S;
80 /// struct UnitStruct {
81 /// attrs: Vec<Attribute>,
82 /// struct_token: Token![struct],
83 /// name: Ident,
84 /// semi_token: Token![;],
85 /// }
86 ///
87 /// impl Parse for UnitStruct {
88 /// fn parse(input: ParseStream) -> Result<Self> {
89 /// Ok(UnitStruct {
90 /// attrs: input.call(Attribute::parse_outer)?,
91 /// struct_token: input.parse()?,
92 /// name: input.parse()?,
93 /// semi_token: input.parse()?,
94 /// })
95 /// }
96 /// }
David Tolnayd8bd15f2018-09-01 16:57:39 -070097 /// ```
David Tolnay9c76bcb2017-12-26 23:14:59 -050098 pub struct Attribute #manual_extra_traits {
David Tolnayf8db7ba2017-11-11 22:52:16 -080099 pub pound_token: Token![#],
David Tolnay4a3f59a2017-12-28 21:21:12 -0500100 pub style: AttrStyle,
David Tolnay32954ef2017-12-26 22:43:16 -0500101 pub bracket_token: token::Bracket,
Alex Crichton62a0a592017-05-22 13:58:53 -0700102 pub path: Path,
David Tolnay369f0c52017-12-27 01:50:45 -0500103 pub tts: TokenStream,
Alex Crichton62a0a592017-05-22 13:58:53 -0700104 }
David Tolnayb79ee962016-09-04 09:39:20 -0700105}
106
David Tolnay9c76bcb2017-12-26 23:14:59 -0500107#[cfg(feature = "extra-traits")]
108impl Eq for Attribute {}
109
110#[cfg(feature = "extra-traits")]
111impl PartialEq for Attribute {
112 fn eq(&self, other: &Self) -> bool {
David Tolnay65fb5662018-05-20 20:02:28 -0700113 self.style == other.style
114 && self.pound_token == other.pound_token
115 && self.bracket_token == other.bracket_token
116 && self.path == other.path
David Tolnay369f0c52017-12-27 01:50:45 -0500117 && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts)
David Tolnay9c76bcb2017-12-26 23:14:59 -0500118 }
119}
120
121#[cfg(feature = "extra-traits")]
122impl Hash for Attribute {
123 fn hash<H>(&self, state: &mut H)
David Tolnay51382052017-12-27 13:46:21 -0500124 where
125 H: Hasher,
David Tolnay9c76bcb2017-12-26 23:14:59 -0500126 {
127 self.style.hash(state);
128 self.pound_token.hash(state);
129 self.bracket_token.hash(state);
130 self.path.hash(state);
David Tolnay369f0c52017-12-27 01:50:45 -0500131 TokenStreamHelper(&self.tts).hash(state);
David Tolnay9c76bcb2017-12-26 23:14:59 -0500132 }
133}
134
David Tolnay02d77cc2016-10-02 09:52:08 -0700135impl Attribute {
David Tolnay068120a2018-01-06 23:17:22 -0800136 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
137 /// possible.
David Tolnayf2b744b2018-10-13 14:24:01 -0700138 ///
139 /// Deprecated; use `parse_meta` instead.
140 #[doc(hidden)]
David Tolnayaaadd782018-01-06 22:58:13 -0800141 pub fn interpret_meta(&self) -> Option<Meta> {
David Tolnayf2b744b2018-10-13 14:24:01 -0700142 #[cfg(feature = "parsing")]
143 {
144 self.parse_meta().ok()
Arnavionbf395bf2017-04-15 15:35:22 -0700145 }
146
David Tolnayf2b744b2018-10-13 14:24:01 -0700147 #[cfg(not(feature = "parsing"))]
148 {
149 let name = if self.path.segments.len() == 1 {
150 &self.path.segments.first().unwrap().value().ident
151 } else {
152 return None;
153 };
David Tolnay369f0c52017-12-27 01:50:45 -0500154
David Tolnayf2b744b2018-10-13 14:24:01 -0700155 if self.tts.is_empty() {
156 return Some(Meta::Word(name.clone()));
Arnavionbf395bf2017-04-15 15:35:22 -0700157 }
Arnavionbf395bf2017-04-15 15:35:22 -0700158
David Tolnayf2b744b2018-10-13 14:24:01 -0700159 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
160
161 if tts.len() == 1 {
162 if let Some(meta) = Attribute::extract_meta_list(name.clone(), &tts[0]) {
163 return Some(meta);
164 }
Arnavionbf395bf2017-04-15 15:35:22 -0700165 }
Arnavionbf395bf2017-04-15 15:35:22 -0700166
David Tolnayf2b744b2018-10-13 14:24:01 -0700167 if tts.len() == 2 {
168 if let Some(meta) = Attribute::extract_name_value(name.clone(), &tts[0], &tts[1]) {
169 return Some(meta);
170 }
171 }
172
173 None
174 }
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> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700181 if let Some(ref colon) = self.path.leading_colon {
182 return Err(Error::new(colon.spans[0], "expected meta identifier"));
183 }
Carl Lercheae0fa602018-10-12 21:46:54 -0700184
David Tolnayf1a10262018-10-13 15:33:50 -0700185 let first_segment = self
186 .path
187 .segments
188 .first()
189 .expect("paths have at least one segment");
David Tolnaye2f85af2018-10-13 14:20:43 -0700190 if let Some(colon) = first_segment.punct() {
191 return Err(Error::new(colon.spans[0], "expected meta value"));
192 }
193 let ident = first_segment.value().ident.clone();
Carl Lerche22926d72018-10-12 22:29:11 -0700194
David Tolnaye2f85af2018-10-13 14:20:43 -0700195 let parser = |input: ParseStream| parsing::parse_meta_after_ident(ident, input);
196 parse::Parser::parse2(parser, self.tts.clone())
Carl Lercheae0fa602018-10-12 21:46:54 -0700197 }
198
David Tolnay50660862018-09-01 15:42:53 -0700199 /// Parses zero or more outer attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700200 ///
201 /// *This function is available if Syn is built with the `"parsing"`
202 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700203 #[cfg(feature = "parsing")]
204 pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> {
205 let mut attrs = Vec::new();
206 while input.peek(Token![#]) {
207 attrs.push(input.call(parsing::single_parse_outer)?);
208 }
209 Ok(attrs)
210 }
211
212 /// Parses zero or more inner attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700213 ///
214 /// *This function is available if Syn is built with the `"parsing"`
215 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700216 #[cfg(feature = "parsing")]
217 pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> {
218 let mut attrs = Vec::new();
219 while input.peek(Token![#]) && input.peek2(Token![!]) {
220 attrs.push(input.call(parsing::single_parse_inner)?);
221 }
222 Ok(attrs)
223 }
224
David Tolnayf2b744b2018-10-13 14:24:01 -0700225 #[cfg(not(feature = "parsing"))]
Alex Crichton9a4dca22018-03-28 06:32:19 -0700226 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
227 let g = match *tt {
228 TokenTree::Group(ref g) => g,
229 _ => return None,
230 };
231 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700232 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700233 }
234 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
235 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
236 Some(n) => n,
237 None => return None,
238 };
239 Some(Meta::List(MetaList {
240 paren_token: token::Paren(g.span()),
241 ident: ident,
242 nested: nested,
243 }))
244 }
245
David Tolnayf2b744b2018-10-13 14:24:01 -0700246 #[cfg(not(feature = "parsing"))]
Alex Crichton9a4dca22018-03-28 06:32:19 -0700247 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
248 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700249 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700250 _ => return None,
251 };
252 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700253 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700254 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700255 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700256 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700257 }
258
259 match *b {
260 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
261 Some(Meta::NameValue(MetaNameValue {
262 ident: ident,
263 eq_token: Token![=]([a.span()]),
264 lit: Lit::new(l.clone()),
265 }))
266 }
David Tolnaya4319b72018-06-02 00:49:15 -0700267 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700268 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
269 ident: ident,
270 eq_token: Token![=]([a.span()]),
271 lit: Lit::Bool(LitBool {
272 value: v == "true",
273 span: b.span(),
274 }),
275 })),
276 _ => None,
277 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700278 _ => None,
279 }
280 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700281}
282
David Tolnayf2b744b2018-10-13 14:24:01 -0700283#[cfg(not(feature = "parsing"))]
David Tolnayaaadd782018-01-06 22:58:13 -0800284fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700285 assert!(!tts.is_empty());
286
Alex Crichton9a4dca22018-03-28 06:32:19 -0700287 match tts[0] {
288 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800289 if lit.to_string().starts_with('/') {
290 None
291 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700292 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800293 Some((NestedMeta::Literal(lit), &tts[1..]))
294 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700295 }
296
Alex Crichtona74a1c82018-05-16 10:20:44 -0700297 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700298 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700299 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700300 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700301 }
302 }
303
304 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700305 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700306 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700307 }
308 }
309
David Tolnay4c510042018-09-12 00:04:51 -0700310 let nested_meta = if ident == "true" || ident == "false" {
311 NestedMeta::Literal(Lit::Bool(LitBool {
312 value: ident == "true",
313 span: ident.span(),
314 }))
315 } else {
316 NestedMeta::Meta(Meta::Word(ident.clone()))
317 };
318 Some((nested_meta, &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700319 }
320
David Tolnay51382052017-12-27 13:46:21 -0500321 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700322 }
323}
324
David Tolnayf2b744b2018-10-13 14:24:01 -0700325#[cfg(not(feature = "parsing"))]
David Tolnay51382052017-12-27 13:46:21 -0500326fn list_of_nested_meta_items_from_tokens(
327 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800328) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500329 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700330 let mut first = true;
331
332 while !tts.is_empty() {
333 let prev_comma = if first {
334 first = false;
335 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700336 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700337 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700338 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700339 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700340 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700341 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700342 }
343 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700344 tts = &tts[1..];
345 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500346 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700347 }
348 Some(tok)
349 } else {
David Tolnay51382052017-12-27 13:46:21 -0500350 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700351 };
352 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
353 Some(pair) => pair,
354 None => return None,
355 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500356 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800357 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700358 }
David Tolnay56080682018-01-06 14:01:52 -0800359 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700360 tts = rest;
361 }
362
David Tolnayf2cfd722017-12-31 18:02:51 -0500363 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700364}
365
Alex Crichton62a0a592017-05-22 13:58:53 -0700366ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800367 /// Distinguishes between attributes that decorate an item and attributes
368 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800369 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800370 /// *This type is available if Syn is built with the `"derive"` or `"full"`
371 /// feature.*
372 ///
David Tolnay23557142018-01-06 22:45:40 -0800373 /// # Outer attributes
374 ///
375 /// - `#[repr(transparent)]`
376 /// - `/// # Example`
377 /// - `/** Please file an issue */`
378 ///
379 /// # Inner attributes
380 ///
381 /// - `#![feature(proc_macro)]`
382 /// - `//! # Example`
383 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700384 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700385 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700386 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800387 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700388 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700389}
390
Alex Crichton62a0a592017-05-22 13:58:53 -0700391ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800392 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700393 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800394 /// *This type is available if Syn is built with the `"derive"` or `"full"`
395 /// feature.*
396 ///
David Tolnay068120a2018-01-06 23:17:22 -0800397 /// ## Word
398 ///
399 /// A meta word is like the `test` in `#[test]`.
400 ///
401 /// ## List
402 ///
403 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
404 ///
405 /// ## NameValue
406 ///
407 /// A name-value meta is like the `path = "..."` in `#[path =
408 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800409 ///
410 /// # Syntax tree enum
411 ///
412 /// This type is a [syntax tree enum].
413 ///
414 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800415 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800416 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800417 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800418 ///
419 /// *This type is available if Syn is built with the `"derive"` or
420 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800421 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700422 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500423 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800424 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700425 }),
David Tolnay068120a2018-01-06 23:17:22 -0800426 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800427 ///
428 /// *This type is available if Syn is built with the `"derive"` or
429 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700430 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700431 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800432 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700433 pub lit: Lit,
434 }),
435 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700436}
437
David Tolnayaaadd782018-01-06 22:58:13 -0800438impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800439 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700440 ///
David Tolnay068120a2018-01-06 23:17:22 -0800441 /// For example this would return the `test` in `#[test]`, the `derive` in
442 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
443 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700444 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700445 Meta::Word(ref meta) => meta.clone(),
446 Meta::List(ref meta) => meta.ident.clone(),
447 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700448 }
449 }
David Tolnay8e661e22016-09-27 00:00:04 -0700450}
451
Alex Crichton62a0a592017-05-22 13:58:53 -0700452ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800453 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800454 ///
455 /// *This type is available if Syn is built with the `"derive"` or `"full"`
456 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800457 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800458 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
459 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800460 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500461
David Tolnay068120a2018-01-06 23:17:22 -0800462 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700463 pub Literal(Lit),
464 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700465}
466
David Tolnay161f2de2018-10-13 14:38:20 -0700467/// Conventional argument type associated with an invocation of an attribute
468/// macro.
469///
470/// For example if we are developing an attribute macro that is intended to be
471/// invoked on function items as follows:
472///
David Tolnay95989db2019-01-01 15:05:57 -0500473/// ```edition2018
David Tolnay161f2de2018-10-13 14:38:20 -0700474/// # const IGNORE: &str = stringify! {
475/// #[my_attribute(path = "/v1/refresh")]
476/// # };
477/// pub fn refresh() {
478/// /* ... */
479/// }
480/// ```
481///
482/// The implementation of this macro would want to parse its attribute arguments
483/// as type `AttributeArgs`.
484///
David Tolnay95989db2019-01-01 15:05:57 -0500485/// ```edition2018
David Tolnay161f2de2018-10-13 14:38:20 -0700486/// extern crate proc_macro;
487///
488/// use proc_macro::TokenStream;
David Tolnayfd5b1172018-12-31 17:54:36 -0500489/// use syn::{parse_macro_input, AttributeArgs, ItemFn};
David Tolnay161f2de2018-10-13 14:38:20 -0700490///
491/// # const IGNORE: &str = stringify! {
492/// #[proc_macro_attribute]
493/// # };
494/// pub fn my_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
495/// let args = parse_macro_input!(args as AttributeArgs);
496/// let input = parse_macro_input!(input as ItemFn);
497///
498/// /* ... */
499/// # "".parse().unwrap()
500/// }
David Tolnay161f2de2018-10-13 14:38:20 -0700501/// ```
502pub type AttributeArgs = Vec<NestedMeta>;
503
David Tolnay4a51dc72016-10-01 00:40:31 -0700504pub trait FilterAttrs<'a> {
505 type Ret: Iterator<Item = &'a Attribute>;
506
507 fn outer(self) -> Self::Ret;
508 fn inner(self) -> Self::Ret;
509}
510
David Tolnaydaaf7742016-10-03 11:11:43 -0700511impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500512where
513 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700514{
David Tolnay4a51dc72016-10-01 00:40:31 -0700515 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
516
517 fn outer(self) -> Self::Ret {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800518 #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))]
David Tolnay4a51dc72016-10-01 00:40:31 -0700519 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700520 match attr.style {
521 AttrStyle::Outer => true,
522 _ => false,
523 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700524 }
525 self.into_iter().filter(is_outer)
526 }
527
528 fn inner(self) -> Self::Ret {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800529 #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))]
David Tolnay4a51dc72016-10-01 00:40:31 -0700530 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700531 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700532 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700533 _ => false,
534 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700535 }
536 self.into_iter().filter(is_inner)
537 }
538}
539
David Tolnay86eca752016-09-04 11:26:41 -0700540#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700541pub mod parsing {
542 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700543
David Tolnay59310132018-10-13 13:56:06 -0700544 use ext::IdentExt;
Carl Lerchefc96cd22018-10-12 20:45:07 -0700545 use parse::{Parse, ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700546 #[cfg(feature = "full")]
547 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700548
David Tolnayd9962eb2018-08-30 16:23:47 -0700549 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
550 let content;
551 Ok(Attribute {
552 pound_token: input.parse()?,
553 style: AttrStyle::Inner(input.parse()?),
554 bracket_token: bracketed!(content in input),
555 path: content.call(Path::parse_mod_style)?,
556 tts: content.parse()?,
557 })
David Tolnay201ef212018-01-01 00:09:14 -0500558 }
559
David Tolnayd9962eb2018-08-30 16:23:47 -0700560 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
561 let content;
562 Ok(Attribute {
563 pound_token: input.parse()?,
564 style: AttrStyle::Outer,
565 bracket_token: bracketed!(content in input),
566 path: content.call(Path::parse_mod_style)?,
567 tts: content.parse()?,
568 })
Alex Crichton954046c2017-05-30 21:49:42 -0700569 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700570
571 #[cfg(feature = "full")]
572 impl private {
573 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
574 let mut attrs = outer;
575 attrs.extend(inner);
576 attrs
577 }
578 }
Carl Lerchefc96cd22018-10-12 20:45:07 -0700579
580 impl Parse for Meta {
581 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700582 let ident = input.call(Ident::parse_any)?;
583 parse_meta_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700584 }
585 }
586
587 impl Parse for MetaList {
588 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700589 let ident = input.call(Ident::parse_any)?;
590 parse_meta_list_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700591 }
592 }
593
594 impl Parse for MetaNameValue {
595 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700596 let ident = input.call(Ident::parse_any)?;
597 parse_meta_name_value_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700598 }
599 }
600
601 impl Parse for NestedMeta {
602 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay59310132018-10-13 13:56:06 -0700603 let ahead = input.fork();
604
David Tolnay79268392018-10-13 19:55:48 -0700605 if ahead.peek(Lit) && !(ahead.peek(LitBool) && ahead.peek2(Token![=])) {
David Tolnay59310132018-10-13 13:56:06 -0700606 input.parse().map(NestedMeta::Literal)
607 } else if ahead.call(Ident::parse_any).is_ok() {
608 input.parse().map(NestedMeta::Meta)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700609 } else {
David Tolnay59310132018-10-13 13:56:06 -0700610 Err(input.error("expected identifier or literal"))
Carl Lerchefc96cd22018-10-12 20:45:07 -0700611 }
612 }
613 }
David Tolnaye2f85af2018-10-13 14:20:43 -0700614
615 pub fn parse_meta_after_ident(ident: Ident, input: ParseStream) -> Result<Meta> {
616 if input.peek(token::Paren) {
617 parse_meta_list_after_ident(ident, input).map(Meta::List)
618 } else if input.peek(Token![=]) {
619 parse_meta_name_value_after_ident(ident, input).map(Meta::NameValue)
620 } else {
621 Ok(Meta::Word(ident))
622 }
623 }
624
625 fn parse_meta_list_after_ident(ident: Ident, input: ParseStream) -> Result<MetaList> {
626 let content;
627 Ok(MetaList {
628 ident: ident,
629 paren_token: parenthesized!(content in input),
630 nested: content.parse_terminated(NestedMeta::parse)?,
631 })
632 }
633
David Tolnayf1a10262018-10-13 15:33:50 -0700634 fn parse_meta_name_value_after_ident(
635 ident: Ident,
636 input: ParseStream,
637 ) -> Result<MetaNameValue> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700638 Ok(MetaNameValue {
639 ident: ident,
640 eq_token: input.parse()?,
641 lit: input.parse()?,
642 })
643 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700644}
David Tolnay87d0b442016-09-04 11:52:12 -0700645
646#[cfg(feature = "printing")]
647mod printing {
648 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700649 use proc_macro2::TokenStream;
650 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700651
652 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700653 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700654 self.pound_token.to_tokens(tokens);
655 if let AttrStyle::Inner(ref b) = self.style {
656 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700657 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700658 self.bracket_token.surround(tokens, |tokens| {
659 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800660 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700661 });
David Tolnay87d0b442016-09-04 11:52:12 -0700662 }
663 }
664
David Tolnayaaadd782018-01-06 22:58:13 -0800665 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700666 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700667 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700668 self.paren_token.surround(tokens, |tokens| {
669 self.nested.to_tokens(tokens);
670 })
David Tolnay87d0b442016-09-04 11:52:12 -0700671 }
672 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700673
Alex Crichton62a0a592017-05-22 13:58:53 -0700674 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700675 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700676 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700677 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700678 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700679 }
680 }
David Tolnay87d0b442016-09-04 11:52:12 -0700681}