blob: 4ab2f0f3f2769951dbfe30b9d6abab93a1ef2907 [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 Tolnayf2b744b2018-10-13 14:24:01 -070014#[cfg(not(feature = "parsing"))]
15use proc_macro2::{Delimiter, Spacing, TokenTree};
16use proc_macro2::TokenStream;
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 Tolnay068120a2018-01-06 23:17:22 -080060 /// Use the [`interpret_meta`] method to try parsing the tokens of an
61 /// attribute into the structured representation that is used by convention
62 /// across most Rust libraries.
David Tolnay23557142018-01-06 22:45:40 -080063 ///
David Tolnay068120a2018-01-06 23:17:22 -080064 /// [`interpret_meta`]: #method.interpret_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 Tolnaye2f85af2018-10-13 14:20:43 -0700198 let first_segment = self.path.segments.first().expect("paths have at least one segment");
199 if let Some(colon) = first_segment.punct() {
200 return Err(Error::new(colon.spans[0], "expected meta value"));
201 }
202 let ident = first_segment.value().ident.clone();
Carl Lerche22926d72018-10-12 22:29:11 -0700203
David Tolnaye2f85af2018-10-13 14:20:43 -0700204 let parser = |input: ParseStream| parsing::parse_meta_after_ident(ident, input);
205 parse::Parser::parse2(parser, self.tts.clone())
Carl Lercheae0fa602018-10-12 21:46:54 -0700206 }
207
David Tolnay50660862018-09-01 15:42:53 -0700208 /// Parses zero or more outer attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700209 ///
210 /// *This function is available if Syn is built with the `"parsing"`
211 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700212 #[cfg(feature = "parsing")]
213 pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> {
214 let mut attrs = Vec::new();
215 while input.peek(Token![#]) {
216 attrs.push(input.call(parsing::single_parse_outer)?);
217 }
218 Ok(attrs)
219 }
220
221 /// Parses zero or more inner attributes from the stream.
David Tolnay206edfb2018-09-01 16:02:20 -0700222 ///
223 /// *This function is available if Syn is built with the `"parsing"`
224 /// feature.*
David Tolnay50660862018-09-01 15:42:53 -0700225 #[cfg(feature = "parsing")]
226 pub fn parse_inner(input: ParseStream) -> Result<Vec<Self>> {
227 let mut attrs = Vec::new();
228 while input.peek(Token![#]) && input.peek2(Token![!]) {
229 attrs.push(input.call(parsing::single_parse_inner)?);
230 }
231 Ok(attrs)
232 }
233
David Tolnayf2b744b2018-10-13 14:24:01 -0700234 #[cfg(not(feature = "parsing"))]
Alex Crichton9a4dca22018-03-28 06:32:19 -0700235 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
236 let g = match *tt {
237 TokenTree::Group(ref g) => g,
238 _ => return None,
239 };
240 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700241 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700242 }
243 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
244 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
245 Some(n) => n,
246 None => return None,
247 };
248 Some(Meta::List(MetaList {
249 paren_token: token::Paren(g.span()),
250 ident: ident,
251 nested: nested,
252 }))
253 }
254
David Tolnayf2b744b2018-10-13 14:24:01 -0700255 #[cfg(not(feature = "parsing"))]
Alex Crichton9a4dca22018-03-28 06:32:19 -0700256 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
257 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700258 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700259 _ => return None,
260 };
261 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700262 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700263 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700264 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700265 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700266 }
267
268 match *b {
269 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
270 Some(Meta::NameValue(MetaNameValue {
271 ident: ident,
272 eq_token: Token![=]([a.span()]),
273 lit: Lit::new(l.clone()),
274 }))
275 }
David Tolnaya4319b72018-06-02 00:49:15 -0700276 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700277 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
278 ident: ident,
279 eq_token: Token![=]([a.span()]),
280 lit: Lit::Bool(LitBool {
281 value: v == "true",
282 span: b.span(),
283 }),
284 })),
285 _ => None,
286 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700287 _ => None,
288 }
289 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700290}
291
David Tolnayf2b744b2018-10-13 14:24:01 -0700292#[cfg(not(feature = "parsing"))]
David Tolnayaaadd782018-01-06 22:58:13 -0800293fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700294 assert!(!tts.is_empty());
295
Alex Crichton9a4dca22018-03-28 06:32:19 -0700296 match tts[0] {
297 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800298 if lit.to_string().starts_with('/') {
299 None
300 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700301 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800302 Some((NestedMeta::Literal(lit), &tts[1..]))
303 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700304 }
305
Alex Crichtona74a1c82018-05-16 10:20:44 -0700306 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700307 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700308 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700309 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700310 }
311 }
312
313 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700314 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700315 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700316 }
317 }
318
David Tolnay4c510042018-09-12 00:04:51 -0700319 let nested_meta = if ident == "true" || ident == "false" {
320 NestedMeta::Literal(Lit::Bool(LitBool {
321 value: ident == "true",
322 span: ident.span(),
323 }))
324 } else {
325 NestedMeta::Meta(Meta::Word(ident.clone()))
326 };
327 Some((nested_meta, &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700328 }
329
David Tolnay51382052017-12-27 13:46:21 -0500330 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700331 }
332}
333
David Tolnayf2b744b2018-10-13 14:24:01 -0700334#[cfg(not(feature = "parsing"))]
David Tolnay51382052017-12-27 13:46:21 -0500335fn list_of_nested_meta_items_from_tokens(
336 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800337) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500338 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700339 let mut first = true;
340
341 while !tts.is_empty() {
342 let prev_comma = if first {
343 first = false;
344 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700345 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700346 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700347 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700348 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700349 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700350 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700351 }
352 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700353 tts = &tts[1..];
354 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500355 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700356 }
357 Some(tok)
358 } else {
David Tolnay51382052017-12-27 13:46:21 -0500359 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700360 };
361 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
362 Some(pair) => pair,
363 None => return None,
364 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500365 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800366 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700367 }
David Tolnay56080682018-01-06 14:01:52 -0800368 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700369 tts = rest;
370 }
371
David Tolnayf2cfd722017-12-31 18:02:51 -0500372 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700373}
374
Alex Crichton62a0a592017-05-22 13:58:53 -0700375ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800376 /// Distinguishes between attributes that decorate an item and attributes
377 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800378 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800379 /// *This type is available if Syn is built with the `"derive"` or `"full"`
380 /// feature.*
381 ///
David Tolnay23557142018-01-06 22:45:40 -0800382 /// # Outer attributes
383 ///
384 /// - `#[repr(transparent)]`
385 /// - `/// # Example`
386 /// - `/** Please file an issue */`
387 ///
388 /// # Inner attributes
389 ///
390 /// - `#![feature(proc_macro)]`
391 /// - `//! # Example`
392 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700393 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700394 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700395 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800396 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700397 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700398}
399
Alex Crichton62a0a592017-05-22 13:58:53 -0700400ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800401 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700402 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800403 /// *This type is available if Syn is built with the `"derive"` or `"full"`
404 /// feature.*
405 ///
David Tolnay068120a2018-01-06 23:17:22 -0800406 /// ## Word
407 ///
408 /// A meta word is like the `test` in `#[test]`.
409 ///
410 /// ## List
411 ///
412 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
413 ///
414 /// ## NameValue
415 ///
416 /// A name-value meta is like the `path = "..."` in `#[path =
417 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800418 ///
419 /// # Syntax tree enum
420 ///
421 /// This type is a [syntax tree enum].
422 ///
423 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800424 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800425 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800426 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800427 ///
428 /// *This type is available if Syn is built with the `"derive"` or
429 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800430 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700431 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500432 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800433 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700434 }),
David Tolnay068120a2018-01-06 23:17:22 -0800435 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800436 ///
437 /// *This type is available if Syn is built with the `"derive"` or
438 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700439 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700440 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800441 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700442 pub lit: Lit,
443 }),
444 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700445}
446
David Tolnayaaadd782018-01-06 22:58:13 -0800447impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800448 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700449 ///
David Tolnay068120a2018-01-06 23:17:22 -0800450 /// For example this would return the `test` in `#[test]`, the `derive` in
451 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
452 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700453 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700454 Meta::Word(ref meta) => meta.clone(),
455 Meta::List(ref meta) => meta.ident.clone(),
456 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700457 }
458 }
David Tolnay8e661e22016-09-27 00:00:04 -0700459}
460
Alex Crichton62a0a592017-05-22 13:58:53 -0700461ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800462 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800463 ///
464 /// *This type is available if Syn is built with the `"derive"` or `"full"`
465 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800466 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800467 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
468 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800469 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500470
David Tolnay068120a2018-01-06 23:17:22 -0800471 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700472 pub Literal(Lit),
473 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700474}
475
David Tolnay4a51dc72016-10-01 00:40:31 -0700476pub trait FilterAttrs<'a> {
477 type Ret: Iterator<Item = &'a Attribute>;
478
479 fn outer(self) -> Self::Ret;
480 fn inner(self) -> Self::Ret;
481}
482
David Tolnaydaaf7742016-10-03 11:11:43 -0700483impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500484where
485 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700486{
David Tolnay4a51dc72016-10-01 00:40:31 -0700487 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
488
489 fn outer(self) -> Self::Ret {
490 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700491 match attr.style {
492 AttrStyle::Outer => true,
493 _ => false,
494 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700495 }
496 self.into_iter().filter(is_outer)
497 }
498
499 fn inner(self) -> Self::Ret {
500 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700501 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700502 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700503 _ => false,
504 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700505 }
506 self.into_iter().filter(is_inner)
507 }
508}
509
David Tolnay86eca752016-09-04 11:26:41 -0700510#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700511pub mod parsing {
512 use super::*;
David Tolnayb5f6fc02018-09-01 02:18:50 -0700513
David Tolnay59310132018-10-13 13:56:06 -0700514 use ext::IdentExt;
Carl Lerchefc96cd22018-10-12 20:45:07 -0700515 use parse::{Parse, ParseStream, Result};
David Tolnayb5f6fc02018-09-01 02:18:50 -0700516 #[cfg(feature = "full")]
517 use private;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700518
David Tolnayd9962eb2018-08-30 16:23:47 -0700519 pub fn single_parse_inner(input: ParseStream) -> Result<Attribute> {
520 let content;
521 Ok(Attribute {
522 pound_token: input.parse()?,
523 style: AttrStyle::Inner(input.parse()?),
524 bracket_token: bracketed!(content in input),
525 path: content.call(Path::parse_mod_style)?,
526 tts: content.parse()?,
527 })
David Tolnay201ef212018-01-01 00:09:14 -0500528 }
529
David Tolnayd9962eb2018-08-30 16:23:47 -0700530 pub fn single_parse_outer(input: ParseStream) -> Result<Attribute> {
531 let content;
532 Ok(Attribute {
533 pound_token: input.parse()?,
534 style: AttrStyle::Outer,
535 bracket_token: bracketed!(content in input),
536 path: content.call(Path::parse_mod_style)?,
537 tts: content.parse()?,
538 })
Alex Crichton954046c2017-05-30 21:49:42 -0700539 }
David Tolnayb5f6fc02018-09-01 02:18:50 -0700540
541 #[cfg(feature = "full")]
542 impl private {
543 pub fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
544 let mut attrs = outer;
545 attrs.extend(inner);
546 attrs
547 }
548 }
Carl Lerchefc96cd22018-10-12 20:45:07 -0700549
550 impl Parse for Meta {
551 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700552 let ident = input.call(Ident::parse_any)?;
553 parse_meta_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700554 }
555 }
556
557 impl Parse for MetaList {
558 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700559 let ident = input.call(Ident::parse_any)?;
560 parse_meta_list_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700561 }
562 }
563
564 impl Parse for MetaNameValue {
565 fn parse(input: ParseStream) -> Result<Self> {
David Tolnaye2f85af2018-10-13 14:20:43 -0700566 let ident = input.call(Ident::parse_any)?;
567 parse_meta_name_value_after_ident(ident, input)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700568 }
569 }
570
571 impl Parse for NestedMeta {
572 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay59310132018-10-13 13:56:06 -0700573 let ahead = input.fork();
574
575 if ahead.peek(Lit) {
576 input.parse().map(NestedMeta::Literal)
577 } else if ahead.call(Ident::parse_any).is_ok() {
578 input.parse().map(NestedMeta::Meta)
Carl Lerchefc96cd22018-10-12 20:45:07 -0700579 } else {
David Tolnay59310132018-10-13 13:56:06 -0700580 Err(input.error("expected identifier or literal"))
Carl Lerchefc96cd22018-10-12 20:45:07 -0700581 }
582 }
583 }
David Tolnaye2f85af2018-10-13 14:20:43 -0700584
585 pub fn parse_meta_after_ident(ident: Ident, input: ParseStream) -> Result<Meta> {
586 if input.peek(token::Paren) {
587 parse_meta_list_after_ident(ident, input).map(Meta::List)
588 } else if input.peek(Token![=]) {
589 parse_meta_name_value_after_ident(ident, input).map(Meta::NameValue)
590 } else {
591 Ok(Meta::Word(ident))
592 }
593 }
594
595 fn parse_meta_list_after_ident(ident: Ident, input: ParseStream) -> Result<MetaList> {
596 let content;
597 Ok(MetaList {
598 ident: ident,
599 paren_token: parenthesized!(content in input),
600 nested: content.parse_terminated(NestedMeta::parse)?,
601 })
602 }
603
604 fn parse_meta_name_value_after_ident(ident: Ident, input: ParseStream) -> Result<MetaNameValue> {
605 Ok(MetaNameValue {
606 ident: ident,
607 eq_token: input.parse()?,
608 lit: input.parse()?,
609 })
610 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700611}
David Tolnay87d0b442016-09-04 11:52:12 -0700612
613#[cfg(feature = "printing")]
614mod printing {
615 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700616 use proc_macro2::TokenStream;
617 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700618
619 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700620 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700621 self.pound_token.to_tokens(tokens);
622 if let AttrStyle::Inner(ref b) = self.style {
623 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700624 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700625 self.bracket_token.surround(tokens, |tokens| {
626 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800627 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700628 });
David Tolnay87d0b442016-09-04 11:52:12 -0700629 }
630 }
631
David Tolnayaaadd782018-01-06 22:58:13 -0800632 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700633 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700634 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700635 self.paren_token.surround(tokens, |tokens| {
636 self.nested.to_tokens(tokens);
637 })
David Tolnay87d0b442016-09-04 11:52:12 -0700638 }
639 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700640
Alex Crichton62a0a592017-05-22 13:58:53 -0700641 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700642 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700643 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700644 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700645 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700646 }
647 }
David Tolnay87d0b442016-09-04 11:52:12 -0700648}