blob: 83ad8d773ed6c9a2b45191b49a80b96620886df5 [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
16#[cfg(feature = "extra-traits")]
17use std::hash::{Hash, Hasher};
18#[cfg(feature = "extra-traits")]
David Tolnayc43b44e2017-12-30 23:55:54 -050019use tt::TokenStreamHelper;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070020
Alex Crichton62a0a592017-05-22 13:58:53 -070021ast_struct! {
David Tolnay23557142018-01-06 22:45:40 -080022 /// An attribute like `#[repr(transparent)]`.
23 ///
David Tolnay461d98e2018-01-07 11:07:19 -080024 /// *This type is available if Syn is built with the `"derive"` or `"full"`
25 /// feature.*
26 ///
David Tolnay23557142018-01-06 22:45:40 -080027 /// # Syntax
28 ///
29 /// Rust has six types of attributes.
30 ///
31 /// - Outer attributes like `#[repr(transparent)]`. These appear outside or
32 /// in front of the item they describe.
33 /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
34 /// of the item they describe, usually a module.
35 /// - Outer doc comments like `/// # Example`.
36 /// - Inner doc comments like `//! Please file an issue`.
37 /// - Outer block comments `/** # Example */`.
38 /// - Inner block comments `/*! Please file an issue */`.
39 ///
40 /// The `style` field of type `AttrStyle` distinguishes whether an attribute
41 /// is outer or inner. Doc comments and block comments are promoted to
David Tolnayfe583302018-08-24 16:09:34 -040042 /// attributes, as this is how they are processed by the compiler and by
43 /// `macro_rules!` macros.
David Tolnay23557142018-01-06 22:45:40 -080044 ///
45 /// The `path` field gives the possibly colon-delimited path against which
46 /// the attribute is resolved. It is equal to `"doc"` for desugared doc
47 /// comments. The `tts` field contains the rest of the attribute body as
48 /// tokens.
49 ///
50 /// ```text
51 /// #[derive(Copy)] #[crate::precondition x < 5]
52 /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~
53 /// path tts path tts
54 /// ```
55 ///
David Tolnay068120a2018-01-06 23:17:22 -080056 /// Use the [`interpret_meta`] method to try parsing the tokens of an
57 /// attribute into the structured representation that is used by convention
58 /// across most Rust libraries.
David Tolnay23557142018-01-06 22:45:40 -080059 ///
David Tolnay068120a2018-01-06 23:17:22 -080060 /// [`interpret_meta`]: #method.interpret_meta
David Tolnay9c76bcb2017-12-26 23:14:59 -050061 pub struct Attribute #manual_extra_traits {
David Tolnayf8db7ba2017-11-11 22:52:16 -080062 pub pound_token: Token![#],
David Tolnay4a3f59a2017-12-28 21:21:12 -050063 pub style: AttrStyle,
David Tolnay32954ef2017-12-26 22:43:16 -050064 pub bracket_token: token::Bracket,
Alex Crichton62a0a592017-05-22 13:58:53 -070065 pub path: Path,
David Tolnay369f0c52017-12-27 01:50:45 -050066 pub tts: TokenStream,
Alex Crichton62a0a592017-05-22 13:58:53 -070067 }
David Tolnayb79ee962016-09-04 09:39:20 -070068}
69
David Tolnay9c76bcb2017-12-26 23:14:59 -050070#[cfg(feature = "extra-traits")]
71impl Eq for Attribute {}
72
73#[cfg(feature = "extra-traits")]
74impl PartialEq for Attribute {
75 fn eq(&self, other: &Self) -> bool {
David Tolnay65fb5662018-05-20 20:02:28 -070076 self.style == other.style
77 && self.pound_token == other.pound_token
78 && self.bracket_token == other.bracket_token
79 && self.path == other.path
David Tolnay369f0c52017-12-27 01:50:45 -050080 && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts)
David Tolnay9c76bcb2017-12-26 23:14:59 -050081 }
82}
83
84#[cfg(feature = "extra-traits")]
85impl Hash for Attribute {
86 fn hash<H>(&self, state: &mut H)
David Tolnay51382052017-12-27 13:46:21 -050087 where
88 H: Hasher,
David Tolnay9c76bcb2017-12-26 23:14:59 -050089 {
90 self.style.hash(state);
91 self.pound_token.hash(state);
92 self.bracket_token.hash(state);
93 self.path.hash(state);
David Tolnay369f0c52017-12-27 01:50:45 -050094 TokenStreamHelper(&self.tts).hash(state);
David Tolnay9c76bcb2017-12-26 23:14:59 -050095 }
96}
97
David Tolnay02d77cc2016-10-02 09:52:08 -070098impl Attribute {
David Tolnay068120a2018-01-06 23:17:22 -080099 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
100 /// possible.
David Tolnayaaadd782018-01-06 22:58:13 -0800101 pub fn interpret_meta(&self) -> Option<Meta> {
Arnavion95f8a7a2017-04-19 03:29:56 -0700102 let name = if self.path.segments.len() == 1 {
David Tolnay56080682018-01-06 14:01:52 -0800103 &self.path.segments.first().unwrap().value().ident
Arnavion95f8a7a2017-04-19 03:29:56 -0700104 } else {
105 return None;
106 };
107
Arnavionbf395bf2017-04-15 15:35:22 -0700108 if self.tts.is_empty() {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700109 return Some(Meta::Word(name.clone()));
Arnavionbf395bf2017-04-15 15:35:22 -0700110 }
111
David Tolnay369f0c52017-12-27 01:50:45 -0500112 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
113
114 if tts.len() == 1 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700115 if let Some(meta) = Attribute::extract_meta_list(name.clone(), &tts[0]) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700116 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700117 }
118 }
119
David Tolnay369f0c52017-12-27 01:50:45 -0500120 if tts.len() == 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700121 if let Some(meta) = Attribute::extract_name_value(name.clone(), &tts[0], &tts[1]) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700122 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700123 }
124 }
125
126 None
David Tolnay02d77cc2016-10-02 09:52:08 -0700127 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700128
129 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
130 let g = match *tt {
131 TokenTree::Group(ref g) => g,
132 _ => return None,
133 };
134 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700135 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700136 }
137 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
138 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
139 Some(n) => n,
140 None => return None,
141 };
142 Some(Meta::List(MetaList {
143 paren_token: token::Paren(g.span()),
144 ident: ident,
145 nested: nested,
146 }))
147 }
148
149 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
150 let a = match *a {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700151 TokenTree::Punct(ref o) => o,
Alex Crichton9a4dca22018-03-28 06:32:19 -0700152 _ => return None,
153 };
154 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700155 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700156 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700157 if a.as_char() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700158 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700159 }
160
161 match *b {
162 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
163 Some(Meta::NameValue(MetaNameValue {
164 ident: ident,
165 eq_token: Token![=]([a.span()]),
166 lit: Lit::new(l.clone()),
167 }))
168 }
David Tolnaya4319b72018-06-02 00:49:15 -0700169 TokenTree::Ident(ref v) => match &v.to_string()[..] {
David Tolnay94d2b792018-04-29 12:26:10 -0700170 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
171 ident: ident,
172 eq_token: Token![=]([a.span()]),
173 lit: Lit::Bool(LitBool {
174 value: v == "true",
175 span: b.span(),
176 }),
177 })),
178 _ => None,
179 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700180 _ => None,
181 }
182 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700183}
184
David Tolnayaaadd782018-01-06 22:58:13 -0800185fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700186 assert!(!tts.is_empty());
187
Alex Crichton9a4dca22018-03-28 06:32:19 -0700188 match tts[0] {
189 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800190 if lit.to_string().starts_with('/') {
191 None
192 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700193 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800194 Some((NestedMeta::Literal(lit), &tts[1..]))
195 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700196 }
197
Alex Crichtona74a1c82018-05-16 10:20:44 -0700198 TokenTree::Ident(ref ident) => {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700199 if tts.len() >= 3 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700200 if let Some(meta) = Attribute::extract_name_value(ident.clone(), &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700201 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700202 }
203 }
204
205 if tts.len() >= 2 {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700206 if let Some(meta) = Attribute::extract_meta_list(ident.clone(), &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700207 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700208 }
209 }
210
Alex Crichtona74a1c82018-05-16 10:20:44 -0700211 Some((Meta::Word(ident.clone()).into(), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700212 }
213
David Tolnay51382052017-12-27 13:46:21 -0500214 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700215 }
216}
217
David Tolnay51382052017-12-27 13:46:21 -0500218fn list_of_nested_meta_items_from_tokens(
219 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800220) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500221 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700222 let mut first = true;
223
224 while !tts.is_empty() {
225 let prev_comma = if first {
226 first = false;
227 None
Alex Crichtona74a1c82018-05-16 10:20:44 -0700228 } else if let TokenTree::Punct(ref op) = tts[0] {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700229 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700230 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700231 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700232 if op.as_char() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700233 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700234 }
235 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700236 tts = &tts[1..];
237 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500238 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700239 }
240 Some(tok)
241 } else {
David Tolnay51382052017-12-27 13:46:21 -0500242 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700243 };
244 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
245 Some(pair) => pair,
246 None => return None,
247 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500248 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800249 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700250 }
David Tolnay56080682018-01-06 14:01:52 -0800251 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700252 tts = rest;
253 }
254
David Tolnayf2cfd722017-12-31 18:02:51 -0500255 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700256}
257
Alex Crichton62a0a592017-05-22 13:58:53 -0700258ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800259 /// Distinguishes between attributes that decorate an item and attributes
260 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800261 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800262 /// *This type is available if Syn is built with the `"derive"` or `"full"`
263 /// feature.*
264 ///
David Tolnay23557142018-01-06 22:45:40 -0800265 /// # Outer attributes
266 ///
267 /// - `#[repr(transparent)]`
268 /// - `/// # Example`
269 /// - `/** Please file an issue */`
270 ///
271 /// # Inner attributes
272 ///
273 /// - `#![feature(proc_macro)]`
274 /// - `//! # Example`
275 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700276 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700277 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700278 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800279 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700280 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700281}
282
Alex Crichton62a0a592017-05-22 13:58:53 -0700283ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800284 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700285 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800286 /// *This type is available if Syn is built with the `"derive"` or `"full"`
287 /// feature.*
288 ///
David Tolnay068120a2018-01-06 23:17:22 -0800289 /// ## Word
290 ///
291 /// A meta word is like the `test` in `#[test]`.
292 ///
293 /// ## List
294 ///
295 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
296 ///
297 /// ## NameValue
298 ///
299 /// A name-value meta is like the `path = "..."` in `#[path =
300 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800301 ///
302 /// # Syntax tree enum
303 ///
304 /// This type is a [syntax tree enum].
305 ///
306 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800307 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800308 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800309 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800310 ///
311 /// *This type is available if Syn is built with the `"derive"` or
312 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800313 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700314 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500315 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800316 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700317 }),
David Tolnay068120a2018-01-06 23:17:22 -0800318 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800319 ///
320 /// *This type is available if Syn is built with the `"derive"` or
321 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700322 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700323 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800324 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700325 pub lit: Lit,
326 }),
327 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700328}
329
David Tolnayaaadd782018-01-06 22:58:13 -0800330impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800331 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700332 ///
David Tolnay068120a2018-01-06 23:17:22 -0800333 /// For example this would return the `test` in `#[test]`, the `derive` in
334 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
335 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700336 match *self {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700337 Meta::Word(ref meta) => meta.clone(),
338 Meta::List(ref meta) => meta.ident.clone(),
339 Meta::NameValue(ref meta) => meta.ident.clone(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700340 }
341 }
David Tolnay8e661e22016-09-27 00:00:04 -0700342}
343
Alex Crichton62a0a592017-05-22 13:58:53 -0700344ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800345 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800346 ///
347 /// *This type is available if Syn is built with the `"derive"` or `"full"`
348 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800349 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800350 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
351 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800352 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500353
David Tolnay068120a2018-01-06 23:17:22 -0800354 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700355 pub Literal(Lit),
356 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700357}
358
David Tolnay4a51dc72016-10-01 00:40:31 -0700359pub trait FilterAttrs<'a> {
360 type Ret: Iterator<Item = &'a Attribute>;
361
362 fn outer(self) -> Self::Ret;
363 fn inner(self) -> Self::Ret;
364}
365
David Tolnaydaaf7742016-10-03 11:11:43 -0700366impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500367where
368 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700369{
David Tolnay4a51dc72016-10-01 00:40:31 -0700370 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
371
372 fn outer(self) -> Self::Ret {
373 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700374 match attr.style {
375 AttrStyle::Outer => true,
376 _ => false,
377 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700378 }
379 self.into_iter().filter(is_outer)
380 }
381
382 fn inner(self) -> Self::Ret {
383 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700384 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700385 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700386 _ => false,
387 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700388 }
389 self.into_iter().filter(is_inner)
390 }
391}
392
David Tolnay86eca752016-09-04 11:26:41 -0700393#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700394pub mod parsing {
395 use super::*;
David Tolnaydfc886b2018-01-06 08:03:09 -0800396 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500397 use parse_error;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700398 use proc_macro2::{Literal, Punct, Spacing, Span, TokenTree};
David Tolnay203557a2017-12-27 23:59:33 -0500399 use synom::PResult;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700400
David Tolnayf800fc12017-12-27 22:08:48 -0500401 fn eq(span: Span) -> TokenTree {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700402 let mut op = Punct::new('=', Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700403 op.set_span(span);
404 op.into()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700405 }
406
Alex Crichton954046c2017-05-30 21:49:42 -0700407 impl Attribute {
Michael Layzell92639a52017-06-01 00:07:44 -0400408 named!(pub parse_inner -> Self, alt!(
409 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800410 pound: punct!(#) >>
411 bang: punct!(!) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400412 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500413 call!(Path::parse_mod_style),
David Tolnay0235ba62018-07-21 19:20:50 -0700414 syn!(TokenStream),
Michael Layzell92639a52017-06-01 00:07:44 -0400415 )) >>
416 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500417 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700418
Michael Layzell92639a52017-06-01 00:07:44 -0400419 Attribute {
420 style: AttrStyle::Inner(bang),
421 path: path,
422 tts: tts,
Michael Layzell92639a52017-06-01 00:07:44 -0400423 pound_token: pound,
424 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700425 }
Michael Layzell92639a52017-06-01 00:07:44 -0400426 })
427 )
428 |
429 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500430 call!(lit_doc_comment, Comment::Inner),
David Tolnayf800fc12017-12-27 22:08:48 -0500431 |lit| {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700432 let span = lit.span();
David Tolnayf800fc12017-12-27 22:08:48 -0500433 Attribute {
David Tolnay7ac699c2018-08-24 14:00:58 -0400434 style: AttrStyle::Inner(Token![!](span)),
David Tolnayf800fc12017-12-27 22:08:48 -0500435 path: Ident::new("doc", span).into(),
436 tts: vec![
437 eq(span),
438 lit,
439 ].into_iter().collect(),
David Tolnay7ac699c2018-08-24 14:00:58 -0400440 pound_token: Token![#](span),
David Tolnayf800fc12017-12-27 22:08:48 -0500441 bracket_token: token::Bracket(span),
442 }
Michael Layzell92639a52017-06-01 00:07:44 -0400443 }
444 )
445 ));
Alex Crichton954046c2017-05-30 21:49:42 -0700446
Michael Layzell92639a52017-06-01 00:07:44 -0400447 named!(pub parse_outer -> Self, alt!(
448 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800449 pound: punct!(#) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400450 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500451 call!(Path::parse_mod_style),
David Tolnay0235ba62018-07-21 19:20:50 -0700452 syn!(TokenStream),
Michael Layzell92639a52017-06-01 00:07:44 -0400453 )) >>
454 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500455 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700456
Michael Layzell92639a52017-06-01 00:07:44 -0400457 Attribute {
Alex Crichton954046c2017-05-30 21:49:42 -0700458 style: AttrStyle::Outer,
Michael Layzell92639a52017-06-01 00:07:44 -0400459 path: path,
460 tts: tts,
Michael Layzell92639a52017-06-01 00:07:44 -0400461 pound_token: pound,
462 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700463 }
Michael Layzell92639a52017-06-01 00:07:44 -0400464 })
465 )
466 |
467 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500468 call!(lit_doc_comment, Comment::Outer),
David Tolnayf800fc12017-12-27 22:08:48 -0500469 |lit| {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700470 let span = lit.span();
David Tolnayf800fc12017-12-27 22:08:48 -0500471 Attribute {
472 style: AttrStyle::Outer,
473 path: Ident::new("doc", span).into(),
474 tts: vec![
475 eq(span),
476 lit,
477 ].into_iter().collect(),
David Tolnay7ac699c2018-08-24 14:00:58 -0400478 pound_token: Token![#](span),
David Tolnayf800fc12017-12-27 22:08:48 -0500479 bracket_token: token::Bracket(span),
480 }
Michael Layzell92639a52017-06-01 00:07:44 -0400481 }
482 )
483 ));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700484 }
David Tolnayb79ee962016-09-04 09:39:20 -0700485
David Tolnay201ef212018-01-01 00:09:14 -0500486 enum Comment {
487 Inner,
488 Outer,
489 }
490
491 fn lit_doc_comment(input: Cursor, style: Comment) -> PResult<TokenTree> {
Michael Layzell589a8f42017-06-02 19:47:01 -0400492 match input.literal() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700493 Some((lit, rest)) => {
David Tolnay201ef212018-01-01 00:09:14 -0500494 let string = lit.to_string();
495 let ok = match style {
David Tolnay61037c62018-01-05 16:21:03 -0800496 Comment::Inner => string.starts_with("//!") || string.starts_with("/*!"),
497 Comment::Outer => string.starts_with("///") || string.starts_with("/**"),
David Tolnay201ef212018-01-01 00:09:14 -0500498 };
499 if ok {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700500 let mut new = Literal::string(&string);
501 new.set_span(lit.span());
502 Ok((new.into(), rest))
Michael Layzell589a8f42017-06-02 19:47:01 -0400503 } else {
504 parse_error()
505 }
506 }
David Tolnay51382052017-12-27 13:46:21 -0500507 _ => parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700508 }
509 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700510}
David Tolnay87d0b442016-09-04 11:52:12 -0700511
512#[cfg(feature = "printing")]
513mod printing {
514 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700515 use proc_macro2::TokenStream;
516 use quote::ToTokens;
David Tolnay87d0b442016-09-04 11:52:12 -0700517
518 impl ToTokens for Attribute {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700519 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700520 self.pound_token.to_tokens(tokens);
521 if let AttrStyle::Inner(ref b) = self.style {
522 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700523 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700524 self.bracket_token.surround(tokens, |tokens| {
525 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800526 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700527 });
David Tolnay87d0b442016-09-04 11:52:12 -0700528 }
529 }
530
David Tolnayaaadd782018-01-06 22:58:13 -0800531 impl ToTokens for MetaList {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700532 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700533 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700534 self.paren_token.surround(tokens, |tokens| {
535 self.nested.to_tokens(tokens);
536 })
David Tolnay87d0b442016-09-04 11:52:12 -0700537 }
538 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700539
Alex Crichton62a0a592017-05-22 13:58:53 -0700540 impl ToTokens for MetaNameValue {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700541 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700542 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700543 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700544 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700545 }
546 }
David Tolnay87d0b442016-09-04 11:52:12 -0700547}