blob: cad96f729fe03ea3199428581acf3368f4008082 [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 Tolnayf1a10262018-10-13 15:33:50 -070014use proc_macro2::TokenStream;
David Tolnayf2b744b2018-10-13 14:24:01 -070015#[cfg(not(feature = "parsing"))]
16use proc_macro2::{Delimiter, Spacing, TokenTree};
David Tolnay9c76bcb2017-12-26 23:14:59 -050017
David Tolnay50660862018-09-01 15:42:53 -070018#[cfg(feature = "parsing")]
19use parse::{ParseStream, Result};
David Tolnay9c76bcb2017-12-26 23:14:59 -050020#[cfg(feature = "extra-traits")]
21use std::hash::{Hash, Hasher};
22#[cfg(feature = "extra-traits")]
David Tolnayc43b44e2017-12-30 23:55:54 -050023use tt::TokenStreamHelper;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070024
Alex Crichton62a0a592017-05-22 13:58:53 -070025ast_struct! {
David Tolnay23557142018-01-06 22:45:40 -080026 /// An attribute like `#[repr(transparent)]`.
27 ///
David Tolnay461d98e2018-01-07 11:07:19 -080028 /// *This type is available if Syn is built with the `"derive"` or `"full"`
29 /// feature.*
30 ///
David Tolnay23557142018-01-06 22:45:40 -080031 /// # Syntax
32 ///
33 /// Rust has six types of attributes.
34 ///
35 /// - Outer attributes like `#[repr(transparent)]`. These appear outside or
36 /// in front of the item they describe.
37 /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
38 /// of the item they describe, usually a module.
39 /// - Outer doc comments like `/// # Example`.
40 /// - Inner doc comments like `//! Please file an issue`.
41 /// - Outer block comments `/** # Example */`.
42 /// - Inner block comments `/*! Please file an issue */`.
43 ///
44 /// The `style` field of type `AttrStyle` distinguishes whether an attribute
45 /// is outer or inner. Doc comments and block comments are promoted to
David Tolnayfe583302018-08-24 16:09:34 -040046 /// attributes, as this is how they are processed by the compiler and by
47 /// `macro_rules!` macros.
David Tolnay23557142018-01-06 22:45:40 -080048 ///
49 /// The `path` field gives the possibly colon-delimited path against which
50 /// the attribute is resolved. It is equal to `"doc"` for desugared doc
51 /// comments. The `tts` field contains the rest of the attribute body as
52 /// tokens.
53 ///
54 /// ```text
55 /// #[derive(Copy)] #[crate::precondition x < 5]
56 /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~
57 /// path tts path tts
58 /// ```
59 ///
David Tolnay4ac734f2018-11-10 14:19:00 -080060 /// Use the [`parse_meta`] method to try parsing the tokens of an attribute
61 /// into the structured representation that is used by convention across
62 /// most Rust libraries.
David Tolnay23557142018-01-06 22:45:40 -080063 ///
Andy Russellce34d592018-11-10 12:10:39 -050064 /// [`parse_meta`]: #method.parse_meta
David Tolnayd8bd15f2018-09-01 16:57:39 -070065 ///
66 /// # Parsing
67 ///
68 /// This type does not implement the [`Parse`] trait and thus cannot be
69 /// parsed directly by [`ParseStream::parse`]. Instead use
70 /// [`ParseStream::call`] with one of the two parser functions
71 /// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
72 /// which you intend to parse.
73 ///
74 /// [`Parse`]: parse/trait.Parse.html
75 /// [`ParseStream::parse`]: parse/struct.ParseBuffer.html#method.parse
76 /// [`ParseStream::call`]: parse/struct.ParseBuffer.html#method.call
77 /// [`Attribute::parse_outer`]: #method.parse_outer
78 /// [`Attribute::parse_inner`]: #method.parse_inner
79 ///
80 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -070081 /// #[macro_use]
82 /// extern crate syn;
83 ///
84 /// use syn::{Attribute, Ident};
David Tolnayd8bd15f2018-09-01 16:57:39 -070085 /// use syn::parse::{Parse, ParseStream, Result};
86 ///
87 /// // Parses a unit struct with attributes.
88 /// //
89 /// // #[path = "s.tmpl"]
90 /// // struct S;
91 /// struct UnitStruct {
92 /// attrs: Vec<Attribute>,
93 /// struct_token: Token![struct],
94 /// name: Ident,
95 /// semi_token: Token![;],
96 /// }
97 ///
98 /// impl Parse for UnitStruct {
99 /// fn parse(input: ParseStream) -> Result<Self> {
100 /// Ok(UnitStruct {
101 /// attrs: input.call(Attribute::parse_outer)?,
102 /// struct_token: input.parse()?,
103 /// name: input.parse()?,
104 /// semi_token: input.parse()?,
105 /// })
106 /// }
107 /// }
108 /// #
109 /// # fn main() {}
110 /// ```
David Tolnay9c76bcb2017-12-26 23:14:59 -0500111 pub struct Attribute #manual_extra_traits {
David Tolnayf8db7ba2017-11-11 22:52:16 -0800112 pub pound_token: Token![#],
David Tolnay4a3f59a2017-12-28 21:21:12 -0500113 pub style: AttrStyle,
David Tolnay32954ef2017-12-26 22:43:16 -0500114 pub bracket_token: token::Bracket,
Alex Crichton62a0a592017-05-22 13:58:53 -0700115 pub path: Path,
David Tolnay369f0c52017-12-27 01:50:45 -0500116 pub tts: TokenStream,
Alex Crichton62a0a592017-05-22 13:58:53 -0700117 }
David Tolnayb79ee962016-09-04 09:39:20 -0700118}
119
David Tolnay9c76bcb2017-12-26 23:14:59 -0500120#[cfg(feature = "extra-traits")]
121impl Eq for Attribute {}
122
123#[cfg(feature = "extra-traits")]
124impl PartialEq for Attribute {
125 fn eq(&self, other: &Self) -> bool {
David Tolnay65fb5662018-05-20 20:02:28 -0700126 self.style == other.style
127 && self.pound_token == other.pound_token
128 && self.bracket_token == other.bracket_token
129 && self.path == other.path
David Tolnay369f0c52017-12-27 01:50:45 -0500130 && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts)
David Tolnay9c76bcb2017-12-26 23:14:59 -0500131 }
132}
133
134#[cfg(feature = "extra-traits")]
135impl Hash for Attribute {
136 fn hash<H>(&self, state: &mut H)
David Tolnay51382052017-12-27 13:46:21 -0500137 where
138 H: Hasher,
David Tolnay9c76bcb2017-12-26 23:14:59 -0500139 {
140 self.style.hash(state);
141 self.pound_token.hash(state);
142 self.bracket_token.hash(state);
143 self.path.hash(state);
David Tolnay369f0c52017-12-27 01:50:45 -0500144 TokenStreamHelper(&self.tts).hash(state);
David Tolnay9c76bcb2017-12-26 23:14:59 -0500145 }
146}
147
David Tolnay02d77cc2016-10-02 09:52:08 -0700148impl Attribute {
David Tolnay068120a2018-01-06 23:17:22 -0800149 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
150 /// possible.
David Tolnayf2b744b2018-10-13 14:24:01 -0700151 ///
152 /// Deprecated; use `parse_meta` instead.
153 #[doc(hidden)]
David Tolnayaaadd782018-01-06 22:58:13 -0800154 pub fn interpret_meta(&self) -> Option<Meta> {
David Tolnayf2b744b2018-10-13 14:24:01 -0700155 #[cfg(feature = "parsing")]
156 {
157 self.parse_meta().ok()
Arnavionbf395bf2017-04-15 15:35:22 -0700158 }
159
David Tolnayf2b744b2018-10-13 14:24:01 -0700160 #[cfg(not(feature = "parsing"))]
161 {
162 let name = if self.path.segments.len() == 1 {
163 &self.path.segments.first().unwrap().value().ident
164 } else {
165 return None;
166 };
David Tolnay369f0c52017-12-27 01:50:45 -0500167
David Tolnayf2b744b2018-10-13 14:24:01 -0700168 if self.tts.is_empty() {
169 return Some(Meta::Word(name.clone()));
Arnavionbf395bf2017-04-15 15:35:22 -0700170 }
Arnavionbf395bf2017-04-15 15:35:22 -0700171
David Tolnayf2b744b2018-10-13 14:24:01 -0700172 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
173
174 if tts.len() == 1 {
175 if let Some(meta) = Attribute::extract_meta_list(name.clone(), &tts[0]) {
176 return Some(meta);
177 }
Arnavionbf395bf2017-04-15 15:35:22 -0700178 }
Arnavionbf395bf2017-04-15 15:35:22 -0700179
David Tolnayf2b744b2018-10-13 14:24:01 -0700180 if tts.len() == 2 {
181 if let Some(meta) = Attribute::extract_name_value(name.clone(), &tts[0], &tts[1]) {
182 return Some(meta);
183 }
184 }
185
186 None
187 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700188 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700189
Carl Lercheae0fa602018-10-12 21:46:54 -0700190 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
191 /// possible.
192 #[cfg(feature = "parsing")]
193 pub fn parse_meta(&self) -> Result<Meta> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700194 if let Some(ref colon) = self.path.leading_colon {
195 return Err(Error::new(colon.spans[0], "expected meta identifier"));
196 }
Carl Lercheae0fa602018-10-12 21:46:54 -0700197
David Tolnayf1a10262018-10-13 15:33:50 -0700198 let first_segment = self
199 .path
200 .segments
201 .first()
202 .expect("paths have at least one segment");
David Tolnaye2f85af2018-10-13 14:20:43 -0700203 if let Some(colon) = first_segment.punct() {
204 return Err(Error::new(colon.spans[0], "expected meta value"));
205 }
206 let ident = first_segment.value().ident.clone();
Carl Lerche22926d72018-10-12 22:29:11 -0700207
David Tolnaye2f85af2018-10-13 14:20:43 -0700208 let parser = |input: ParseStream| parsing::parse_meta_after_ident(ident, input);
209 parse::Parser::parse2(parser, self.tts.clone())
Carl Lercheae0fa602018-10-12 21:46:54 -0700210 }
211
David Tolnay50660862018-09-01 15:42:53 -0700212 /// Parses zero or more outer 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_outer(input: ParseStream) -> Result<Vec<Self>> {
218 let mut attrs = Vec::new();
219 while input.peek(Token![#]) {
220 attrs.push(input.call(parsing::single_parse_outer)?);
221 }
222 Ok(attrs)
223 }
224
225 /// Parses zero or more inner attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700226 ///
227 /// *This function is available if Syn is built with the `"parsing"`
228 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700229 #[cfg(feature = "parsing")]
230 pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> {
231 let mut attrs = Vec::new();
232 while input.peek(Token![#]) && input.peek2(Token![!]) {
233 attrs.push(input.call(parsing::single_parse_inner)?);
234 }
235 Ok(attrs)
236 }
237
David Tolnayf2b744b2018-10-13 14:24:01 -0700238 #[cfg(not(feature = "parsing"))]
Alex Crichton9a4dca22018-03-28 06:32:19 -0700239 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
240 let g = match *tt {
241 TokenTree::Group(ref g) => g,
242 _ => return None,
243 };
244 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700245 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700246 }
247 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
248 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
249 Some(n) => n,
250 None => return None,
251 };
252 Some(Meta::List(MetaList {
253 paren_token: token::Paren(g.span()),
254 ident: ident,
255 nested: nested,
256 }))
257 }
258
David Tolnayf2b744b2018-10-13 14:24:01 -0700259 #[cfg(not(feature = "parsing"))]
Alex Crichton9a4dca22018-03-28 06:32:19 -0700260 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
261 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700262 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700263 _ => return None,
264 };
265 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700266 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700267 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700268 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700269 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700270 }
271
272 match *b {
273 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
274 Some(Meta::NameValue(MetaNameValue {
275 ident: ident,
276 eq_token: Token![=]([a.span()]),
277 lit: Lit::new(l.clone()),
278 }))
279 }
David Tolnaya4319b72018-06-02 00:49:15 -0700280 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700281 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
282 ident: ident,
283 eq_token: Token![=]([a.span()]),
284 lit: Lit::Bool(LitBool {
285 value: v == "true",
286 span: b.span(),
287 }),
288 })),
289 _ => None,
290 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700291 _ => None,
292 }
293 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700294}
295
David Tolnayf2b744b2018-10-13 14:24:01 -0700296#[cfg(not(feature = "parsing"))]
David Tolnayaaadd782018-01-06 22:58:13 -0800297fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700298 assert!(!tts.is_empty());
299
Alex Crichton9a4dca22018-03-28 06:32:19 -0700300 match tts[0] {
301 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800302 if lit.to_string().starts_with('/') {
303 None
304 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700305 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800306 Some((NestedMeta::Literal(lit), &tts[1..]))
307 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700308 }
309
Alex Crichtona74a1c82018-05-16 10:20:44 -0700310 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700311 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700312 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700313 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700314 }
315 }
316
317 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700318 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700319 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700320 }
321 }
322
David Tolnay4c510042018-09-12 00:04:51 -0700323 let nested_meta = if ident == "true" || ident == "false" {
324 NestedMeta::Literal(Lit::Bool(LitBool {
325 value: ident == "true",
326 span: ident.span(),
327 }))
328 } else {
329 NestedMeta::Meta(Meta::Word(ident.clone()))
330 };
331 Some((nested_meta, &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700332 }
333
David Tolnay51382052017-12-27 13:46:21 -0500334 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700335 }
336}
337
David Tolnayf2b744b2018-10-13 14:24:01 -0700338#[cfg(not(feature = "parsing"))]
David Tolnay51382052017-12-27 13:46:21 -0500339fn list_of_nested_meta_items_from_tokens(
340 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800341) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500342 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700343 let mut first = true;
344
345 while !tts.is_empty() {
346 let prev_comma = if first {
347 first = false;
348 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700349 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700350 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700351 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700352 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700353 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700354 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700355 }
356 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700357 tts = &tts[1..];
358 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500359 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700360 }
361 Some(tok)
362 } else {
David Tolnay51382052017-12-27 13:46:21 -0500363 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700364 };
365 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
366 Some(pair) => pair,
367 None => return None,
368 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500369 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800370 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700371 }
David Tolnay56080682018-01-06 14:01:52 -0800372 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700373 tts = rest;
374 }
375
David Tolnayf2cfd722017-12-31 18:02:51 -0500376 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700377}
378
Alex Crichton62a0a592017-05-22 13:58:53 -0700379ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800380 /// Distinguishes between attributes that decorate an item and attributes
381 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800382 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800383 /// *This type is available if Syn is built with the `"derive"` or `"full"`
384 /// feature.*
385 ///
David Tolnay23557142018-01-06 22:45:40 -0800386 /// # Outer attributes
387 ///
388 /// - `#[repr(transparent)]`
389 /// - `/// # Example`
390 /// - `/** Please file an issue */`
391 ///
392 /// # Inner attributes
393 ///
394 /// - `#![feature(proc_macro)]`
395 /// - `//! # Example`
396 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700397 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700398 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700399 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800400 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700401 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700402}
403
Alex Crichton62a0a592017-05-22 13:58:53 -0700404ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800405 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700406 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800407 /// *This type is available if Syn is built with the `"derive"` or `"full"`
408 /// feature.*
409 ///
David Tolnay068120a2018-01-06 23:17:22 -0800410 /// ## Word
411 ///
412 /// A meta word is like the `test` in `#[test]`.
413 ///
414 /// ## List
415 ///
416 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
417 ///
418 /// ## NameValue
419 ///
420 /// A name-value meta is like the `path = "..."` in `#[path =
421 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800422 ///
423 /// # Syntax tree enum
424 ///
425 /// This type is a [syntax tree enum].
426 ///
427 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800428 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800429 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800430 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800431 ///
432 /// *This type is available if Syn is built with the `"derive"` or
433 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800434 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700435 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500436 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800437 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700438 }),
David Tolnay068120a2018-01-06 23:17:22 -0800439 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800440 ///
441 /// *This type is available if Syn is built with the `"derive"` or
442 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700443 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700444 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800445 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700446 pub lit: Lit,
447 }),
448 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700449}
450
David Tolnayaaadd782018-01-06 22:58:13 -0800451impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800452 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700453 ///
David Tolnay068120a2018-01-06 23:17:22 -0800454 /// For example this would return the `test` in `#[test]`, the `derive` in
455 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
456 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700457 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700458 Meta::Word(ref meta) => meta.clone(),
459 Meta::List(ref meta) => meta.ident.clone(),
460 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700461 }
462 }
David Tolnay8e661e22016-09-27 00:00:04 -0700463}
464
Alex Crichton62a0a592017-05-22 13:58:53 -0700465ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800466 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800467 ///
468 /// *This type is available if Syn is built with the `"derive"` or `"full"`
469 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800470 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800471 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
472 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800473 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500474
David Tolnay068120a2018-01-06 23:17:22 -0800475 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700476 pub Literal(Lit),
477 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700478}
479
David Tolnay161f2de2018-10-13 14:38:20 -0700480/// Conventional argument type associated with an invocation of an attribute
481/// macro.
482///
483/// For example if we are developing an attribute macro that is intended to be
484/// invoked on function items as follows:
485///
486/// ```rust
487/// # const IGNORE: &str = stringify! {
488/// #[my_attribute(path = "/v1/refresh")]
489/// # };
490/// pub fn refresh() {
491/// /* ... */
492/// }
493/// ```
494///
495/// The implementation of this macro would want to parse its attribute arguments
496/// as type `AttributeArgs`.
497///
498/// ```rust
499/// #[macro_use]
500/// extern crate syn;
501///
502/// extern crate proc_macro;
503///
504/// use proc_macro::TokenStream;
505/// use syn::{AttributeArgs, ItemFn};
506///
507/// # const IGNORE: &str = stringify! {
508/// #[proc_macro_attribute]
509/// # };
510/// pub fn my_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
511/// let args = parse_macro_input!(args as AttributeArgs);
512/// let input = parse_macro_input!(input as ItemFn);
513///
514/// /* ... */
515/// # "".parse().unwrap()
516/// }
517/// #
518/// # fn main() {}
519/// ```
520pub type AttributeArgs = Vec<NestedMeta>;
521
David Tolnay4a51dc72016-10-01 00:40:31 -0700522pub trait FilterAttrs<'a> {
523 type Ret: Iterator<Item = &'a Attribute>;
524
525 fn outer(self) -> Self::Ret;
526 fn inner(self) -> Self::Ret;
527}
528
David Tolnaydaaf7742016-10-03 11:11:43 -0700529impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500530where
531 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700532{
David Tolnay4a51dc72016-10-01 00:40:31 -0700533 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
534
535 fn outer(self) -> Self::Ret {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800536 #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))]
David Tolnay4a51dc72016-10-01 00:40:31 -0700537 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700538 match attr.style {
539 AttrStyle::Outer => true,
540 _ => false,
541 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700542 }
543 self.into_iter().filter(is_outer)
544 }
545
546 fn inner(self) -> Self::Ret {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800547 #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))]
David Tolnay4a51dc72016-10-01 00:40:31 -0700548 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700549 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700550 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700551 _ => false,
552 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700553 }
554 self.into_iter().filter(is_inner)
555 }
556}
557
David Tolnay86eca752016-09-04 11:26:41 -0700558#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700559pub mod parsing {
560 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700561
David Tolnay59310132018-10-13 13:56:06 -0700562 use ext::IdentExt;
Carl Lerchefc96cd22018-10-12 20:45:07 -0700563 use parse::{Parse, ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700564 #[cfg(feature = "full")]
565 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700566
David Tolnayd9962eb2018-08-30 16:23:47 -0700567 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
568 let content;
569 Ok(Attribute {
570 pound_token: input.parse()?,
571 style: AttrStyle::Inner(input.parse()?),
572 bracket_token: bracketed!(content in input),
573 path: content.call(Path::parse_mod_style)?,
574 tts: content.parse()?,
575 })
David Tolnay201ef212018-01-01 00:09:14 -0500576 }
577
David Tolnayd9962eb2018-08-30 16:23:47 -0700578 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
579 let content;
580 Ok(Attribute {
581 pound_token: input.parse()?,
582 style: AttrStyle::Outer,
583 bracket_token: bracketed!(content in input),
584 path: content.call(Path::parse_mod_style)?,
585 tts: content.parse()?,
586 })
Alex Crichton954046c2017-05-30 21:49:42 -0700587 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700588
589 #[cfg(feature = "full")]
590 impl private {
591 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
592 let mut attrs = outer;
593 attrs.extend(inner);
594 attrs
595 }
596 }
Carl Lerchefc96cd22018-10-12 20:45:07 -0700597
598 impl Parse for Meta {
599 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700600 let ident = input.call(Ident::parse_any)?;
601 parse_meta_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700602 }
603 }
604
605 impl Parse for MetaList {
606 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700607 let ident = input.call(Ident::parse_any)?;
608 parse_meta_list_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700609 }
610 }
611
612 impl Parse for MetaNameValue {
613 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700614 let ident = input.call(Ident::parse_any)?;
615 parse_meta_name_value_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700616 }
617 }
618
619 impl Parse for NestedMeta {
620 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay59310132018-10-13 13:56:06 -0700621 let ahead = input.fork();
622
David Tolnay79268392018-10-13 19:55:48 -0700623 if ahead.peek(Lit) && !(ahead.peek(LitBool) && ahead.peek2(Token![=])) {
David Tolnay59310132018-10-13 13:56:06 -0700624 input.parse().map(NestedMeta::Literal)
625 } else if ahead.call(Ident::parse_any).is_ok() {
626 input.parse().map(NestedMeta::Meta)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700627 } else {
David Tolnay59310132018-10-13 13:56:06 -0700628 Err(input.error("expected identifier or literal"))
Carl Lerchefc96cd22018-10-12 20:45:07 -0700629 }
630 }
631 }
David Tolnaye2f85af2018-10-13 14:20:43 -0700632
633 pub fn parse_meta_after_ident(ident: Ident, input: ParseStream) -> Result<Meta> {
634 if input.peek(token::Paren) {
635 parse_meta_list_after_ident(ident, input).map(Meta::List)
636 } else if input.peek(Token![=]) {
637 parse_meta_name_value_after_ident(ident, input).map(Meta::NameValue)
638 } else {
639 Ok(Meta::Word(ident))
640 }
641 }
642
643 fn parse_meta_list_after_ident(ident: Ident, input: ParseStream) -> Result<MetaList> {
644 let content;
645 Ok(MetaList {
646 ident: ident,
647 paren_token: parenthesized!(content in input),
648 nested: content.parse_terminated(NestedMeta::parse)?,
649 })
650 }
651
David Tolnayf1a10262018-10-13 15:33:50 -0700652 fn parse_meta_name_value_after_ident(
653 ident: Ident,
654 input: ParseStream,
655 ) -> Result<MetaNameValue> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700656 Ok(MetaNameValue {
657 ident: ident,
658 eq_token: input.parse()?,
659 lit: input.parse()?,
660 })
661 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700662}
David Tolnay87d0b442016-09-04 11:52:12 -0700663
664#[cfg(feature = "printing")]
665mod printing {
666 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700667 use proc_macro2::TokenStream;
668 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700669
670 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700671 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700672 self.pound_token.to_tokens(tokens);
673 if let AttrStyle::Inner(ref b) = self.style {
674 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700675 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700676 self.bracket_token.surround(tokens, |tokens| {
677 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800678 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700679 });
David Tolnay87d0b442016-09-04 11:52:12 -0700680 }
681 }
682
David Tolnayaaadd782018-01-06 22:58:13 -0800683 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700684 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700685 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700686 self.paren_token.surround(tokens, |tokens| {
687 self.nested.to_tokens(tokens);
688 })
David Tolnay87d0b442016-09-04 11:52:12 -0700689 }
690 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700691
Alex Crichton62a0a592017-05-22 13:58:53 -0700692 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700693 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700694 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700695 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700696 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700697 }
698 }
David Tolnay87d0b442016-09-04 11:52:12 -0700699}