blob: d4cd37353a71d606620b4a3b24dc4c7d1002108d [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 Tolnay51382052017-12-27 13:46:21 -050014use proc_macro2::{Delimiter, Spacing, TokenNode, 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 ///
24 /// # Syntax
25 ///
26 /// Rust has six types of attributes.
27 ///
28 /// - Outer attributes like `#[repr(transparent)]`. These appear outside or
29 /// in front of the item they describe.
30 /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
31 /// of the item they describe, usually a module.
32 /// - Outer doc comments like `/// # Example`.
33 /// - Inner doc comments like `//! Please file an issue`.
34 /// - Outer block comments `/** # Example */`.
35 /// - Inner block comments `/*! Please file an issue */`.
36 ///
37 /// The `style` field of type `AttrStyle` distinguishes whether an attribute
38 /// is outer or inner. Doc comments and block comments are promoted to
39 /// attributes that have `is_sugared_doc` set to true, as this is how they
40 /// are processed by the compiler and by `macro_rules!` macros.
41 ///
42 /// The `path` field gives the possibly colon-delimited path against which
43 /// the attribute is resolved. It is equal to `"doc"` for desugared doc
44 /// comments. The `tts` field contains the rest of the attribute body as
45 /// tokens.
46 ///
47 /// ```text
48 /// #[derive(Copy)] #[crate::precondition x < 5]
49 /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~
50 /// path tts path tts
51 /// ```
52 ///
David Tolnay068120a2018-01-06 23:17:22 -080053 /// Use the [`interpret_meta`] method to try parsing the tokens of an
54 /// attribute into the structured representation that is used by convention
55 /// across most Rust libraries.
David Tolnay23557142018-01-06 22:45:40 -080056 ///
David Tolnay068120a2018-01-06 23:17:22 -080057 /// [`interpret_meta`]: #method.interpret_meta
David Tolnay9c76bcb2017-12-26 23:14:59 -050058 pub struct Attribute #manual_extra_traits {
David Tolnayf8db7ba2017-11-11 22:52:16 -080059 pub pound_token: Token![#],
David Tolnay4a3f59a2017-12-28 21:21:12 -050060 pub style: AttrStyle,
David Tolnay32954ef2017-12-26 22:43:16 -050061 pub bracket_token: token::Bracket,
Alex Crichton62a0a592017-05-22 13:58:53 -070062 pub path: Path,
David Tolnay369f0c52017-12-27 01:50:45 -050063 pub tts: TokenStream,
Alex Crichton62a0a592017-05-22 13:58:53 -070064 pub is_sugared_doc: bool,
65 }
David Tolnayb79ee962016-09-04 09:39:20 -070066}
67
David Tolnay9c76bcb2017-12-26 23:14:59 -050068#[cfg(feature = "extra-traits")]
69impl Eq for Attribute {}
70
71#[cfg(feature = "extra-traits")]
72impl PartialEq for Attribute {
73 fn eq(&self, other: &Self) -> bool {
David Tolnay51382052017-12-27 13:46:21 -050074 self.style == other.style && self.pound_token == other.pound_token
75 && self.bracket_token == other.bracket_token && self.path == other.path
David Tolnay369f0c52017-12-27 01:50:45 -050076 && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts)
David Tolnay9c76bcb2017-12-26 23:14:59 -050077 && self.is_sugared_doc == other.is_sugared_doc
78 }
79}
80
81#[cfg(feature = "extra-traits")]
82impl Hash for Attribute {
83 fn hash<H>(&self, state: &mut H)
David Tolnay51382052017-12-27 13:46:21 -050084 where
85 H: Hasher,
David Tolnay9c76bcb2017-12-26 23:14:59 -050086 {
87 self.style.hash(state);
88 self.pound_token.hash(state);
89 self.bracket_token.hash(state);
90 self.path.hash(state);
David Tolnay369f0c52017-12-27 01:50:45 -050091 TokenStreamHelper(&self.tts).hash(state);
David Tolnay9c76bcb2017-12-26 23:14:59 -050092 self.is_sugared_doc.hash(state);
93 }
94}
95
David Tolnay02d77cc2016-10-02 09:52:08 -070096impl Attribute {
David Tolnay068120a2018-01-06 23:17:22 -080097 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
98 /// possible.
David Tolnayaaadd782018-01-06 22:58:13 -080099 pub fn interpret_meta(&self) -> Option<Meta> {
Arnavion95f8a7a2017-04-19 03:29:56 -0700100 let name = if self.path.segments.len() == 1 {
David Tolnay56080682018-01-06 14:01:52 -0800101 &self.path.segments.first().unwrap().value().ident
Arnavion95f8a7a2017-04-19 03:29:56 -0700102 } else {
103 return None;
104 };
105
Arnavionbf395bf2017-04-15 15:35:22 -0700106 if self.tts.is_empty() {
David Tolnayaaadd782018-01-06 22:58:13 -0800107 return Some(Meta::Word(*name));
Arnavionbf395bf2017-04-15 15:35:22 -0700108 }
109
David Tolnay369f0c52017-12-27 01:50:45 -0500110 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
111
112 if tts.len() == 1 {
113 if let TokenNode::Group(Delimiter::Parenthesis, ref ts) = tts[0].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700114 let tokens = ts.clone().into_iter().collect::<Vec<_>>();
115 if let Some(nested_meta_items) = list_of_nested_meta_items_from_tokens(&tokens) {
David Tolnayaaadd782018-01-06 22:58:13 -0800116 return Some(Meta::List(MetaList {
David Tolnay369f0c52017-12-27 01:50:45 -0500117 paren_token: token::Paren(tts[0].span),
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500118 ident: *name,
Alex Crichton62a0a592017-05-22 13:58:53 -0700119 nested: nested_meta_items,
120 }));
Arnavionbf395bf2017-04-15 15:35:22 -0700121 }
122 }
123 }
124
David Tolnay369f0c52017-12-27 01:50:45 -0500125 if tts.len() == 2 {
126 if let TokenNode::Op('=', Spacing::Alone) = tts[0].kind {
127 if let TokenNode::Literal(ref lit) = tts[1].kind {
David Tolnayaaadd782018-01-06 22:58:13 -0800128 return Some(Meta::NameValue(MetaNameValue {
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500129 ident: *name,
David Tolnay369f0c52017-12-27 01:50:45 -0500130 eq_token: Token![=]([tts[0].span]),
David Tolnay360efd22018-01-04 23:35:26 -0800131 lit: Lit::new(lit.clone(), tts[1].span),
Alex Crichton62a0a592017-05-22 13:58:53 -0700132 }));
Arnavionbf395bf2017-04-15 15:35:22 -0700133 }
Arnavionbf395bf2017-04-15 15:35:22 -0700134 }
135 }
136
137 None
David Tolnay02d77cc2016-10-02 09:52:08 -0700138 }
139}
140
David Tolnayaaadd782018-01-06 22:58:13 -0800141fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700142 assert!(!tts.is_empty());
143
144 match tts[0].kind {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700145 TokenNode::Literal(ref lit) => {
David Tolnay360efd22018-01-04 23:35:26 -0800146 let lit = Lit::new(lit.clone(), tts[0].span);
David Tolnayaaadd782018-01-06 22:58:13 -0800147 Some((NestedMeta::Literal(lit), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700148 }
149
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700150 TokenNode::Term(sym) => {
David Tolnayeb771d72017-12-27 22:11:06 -0500151 let ident = Ident::new(sym.as_str(), tts[0].span);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700152 if tts.len() >= 3 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700153 if let TokenNode::Op('=', Spacing::Alone) = tts[1].kind {
154 if let TokenNode::Literal(ref lit) = tts[2].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700155 let pair = MetaNameValue {
David Tolnayeb771d72017-12-27 22:11:06 -0500156 ident: Ident::new(sym.as_str(), tts[0].span),
David Tolnay98942562017-12-26 21:24:35 -0500157 eq_token: Token![=]([tts[1].span]),
David Tolnay360efd22018-01-04 23:35:26 -0800158 lit: Lit::new(lit.clone(), tts[2].span),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700159 };
David Tolnayaaadd782018-01-06 22:58:13 -0800160 return Some((Meta::NameValue(pair).into(), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700161 }
162 }
163 }
164
165 if tts.len() >= 2 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700166 if let TokenNode::Group(Delimiter::Parenthesis, ref inner_tts) = tts[1].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700167 let inner_tts = inner_tts.clone().into_iter().collect::<Vec<_>>();
168 return match list_of_nested_meta_items_from_tokens(&inner_tts) {
169 Some(nested_meta_items) => {
David Tolnayaaadd782018-01-06 22:58:13 -0800170 let list = MetaList {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700171 ident: ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500172 paren_token: token::Paren(tts[1].span),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700173 nested: nested_meta_items,
174 };
David Tolnayaaadd782018-01-06 22:58:13 -0800175 Some((Meta::List(list).into(), &tts[2..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700176 }
177
David Tolnay51382052017-12-27 13:46:21 -0500178 None => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700179 };
180 }
181 }
182
David Tolnayaaadd782018-01-06 22:58:13 -0800183 Some((Meta::Word(ident).into(), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700184 }
185
David Tolnay51382052017-12-27 13:46:21 -0500186 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700187 }
188}
189
David Tolnay51382052017-12-27 13:46:21 -0500190fn list_of_nested_meta_items_from_tokens(
191 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800192) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500193 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700194 let mut first = true;
195
196 while !tts.is_empty() {
197 let prev_comma = if first {
198 first = false;
199 None
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700200 } else if let TokenNode::Op(',', Spacing::Alone) = tts[0].kind {
David Tolnay98942562017-12-26 21:24:35 -0500201 let tok = Token![,]([tts[0].span]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700202 tts = &tts[1..];
203 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500204 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700205 }
206 Some(tok)
207 } else {
David Tolnay51382052017-12-27 13:46:21 -0500208 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700209 };
210 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
211 Some(pair) => pair,
212 None => return None,
213 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500214 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800215 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700216 }
David Tolnay56080682018-01-06 14:01:52 -0800217 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700218 tts = rest;
219 }
220
David Tolnayf2cfd722017-12-31 18:02:51 -0500221 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700222}
223
Alex Crichton62a0a592017-05-22 13:58:53 -0700224ast_enum! {
225 /// Distinguishes between Attributes that decorate items and Attributes that
David Tolnay23557142018-01-06 22:45:40 -0800226 /// are contained as statements within items.
227 ///
228 /// # Outer attributes
229 ///
230 /// - `#[repr(transparent)]`
231 /// - `/// # Example`
232 /// - `/** Please file an issue */`
233 ///
234 /// # Inner attributes
235 ///
236 /// - `#![feature(proc_macro)]`
237 /// - `//! # Example`
238 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700239 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700240 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700241 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800242 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700243 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700244}
245
Alex Crichton62a0a592017-05-22 13:58:53 -0700246ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800247 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700248 ///
David Tolnay068120a2018-01-06 23:17:22 -0800249 /// ## Word
250 ///
251 /// A meta word is like the `test` in `#[test]`.
252 ///
253 /// ## List
254 ///
255 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
256 ///
257 /// ## NameValue
258 ///
259 /// A name-value meta is like the `path = "..."` in `#[path =
260 /// "sys/windows.rs"]`.
David Tolnayaaadd782018-01-06 22:58:13 -0800261 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800262 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800263 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnayaaadd782018-01-06 22:58:13 -0800264 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700265 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500266 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800267 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700268 }),
David Tolnay068120a2018-01-06 23:17:22 -0800269 /// A name-value pair within an attribute, like `feature = "nightly"`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700270 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700271 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800272 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700273 pub lit: Lit,
274 }),
275 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700276}
277
David Tolnayaaadd782018-01-06 22:58:13 -0800278impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800279 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700280 ///
David Tolnay068120a2018-01-06 23:17:22 -0800281 /// For example this would return the `test` in `#[test]`, the `derive` in
282 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
283 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700284 match *self {
David Tolnay068120a2018-01-06 23:17:22 -0800285 Meta::Word(ref meta) => *meta,
286 Meta::List(ref meta) => meta.ident,
287 Meta::NameValue(ref meta) => meta.ident,
Arnavion95f8a7a2017-04-19 03:29:56 -0700288 }
289 }
David Tolnay8e661e22016-09-27 00:00:04 -0700290}
291
Alex Crichton62a0a592017-05-22 13:58:53 -0700292ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800293 /// Element of a compile-time attribute list.
David Tolnayaaadd782018-01-06 22:58:13 -0800294 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800295 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
296 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800297 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500298
David Tolnay068120a2018-01-06 23:17:22 -0800299 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700300 pub Literal(Lit),
301 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700302}
303
David Tolnay4a51dc72016-10-01 00:40:31 -0700304pub trait FilterAttrs<'a> {
305 type Ret: Iterator<Item = &'a Attribute>;
306
307 fn outer(self) -> Self::Ret;
308 fn inner(self) -> Self::Ret;
309}
310
David Tolnaydaaf7742016-10-03 11:11:43 -0700311impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500312where
313 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700314{
David Tolnay4a51dc72016-10-01 00:40:31 -0700315 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
316
317 fn outer(self) -> Self::Ret {
318 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700319 match attr.style {
320 AttrStyle::Outer => true,
321 _ => false,
322 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700323 }
324 self.into_iter().filter(is_outer)
325 }
326
327 fn inner(self) -> Self::Ret {
328 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700329 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700330 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700331 _ => false,
332 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700333 }
334 self.into_iter().filter(is_inner)
335 }
336}
337
David Tolnay86eca752016-09-04 11:26:41 -0700338#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700339pub mod parsing {
340 use super::*;
David Tolnaydfc886b2018-01-06 08:03:09 -0800341 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500342 use parse_error;
343 use synom::PResult;
David Tolnay61037c62018-01-05 16:21:03 -0800344 use proc_macro2::{Literal, Spacing, Span, TokenNode, TokenTree};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700345
David Tolnayf800fc12017-12-27 22:08:48 -0500346 fn eq(span: Span) -> TokenTree {
Alex Crichton954046c2017-05-30 21:49:42 -0700347 TokenTree {
David Tolnayf800fc12017-12-27 22:08:48 -0500348 span: span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700349 kind: TokenNode::Op('=', Spacing::Alone),
Alex Crichton954046c2017-05-30 21:49:42 -0700350 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700351 }
352
Alex Crichton954046c2017-05-30 21:49:42 -0700353 impl Attribute {
Michael Layzell92639a52017-06-01 00:07:44 -0400354 named!(pub parse_inner -> Self, alt!(
355 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800356 pound: punct!(#) >>
357 bang: punct!(!) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400358 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500359 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500360 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400361 )) >>
362 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500363 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700364
Michael Layzell92639a52017-06-01 00:07:44 -0400365 Attribute {
366 style: AttrStyle::Inner(bang),
367 path: path,
368 tts: tts,
369 is_sugared_doc: false,
370 pound_token: pound,
371 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700372 }
Michael Layzell92639a52017-06-01 00:07:44 -0400373 })
374 )
375 |
376 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500377 call!(lit_doc_comment, Comment::Inner),
David Tolnayf800fc12017-12-27 22:08:48 -0500378 |lit| {
379 let span = lit.span;
380 Attribute {
381 style: AttrStyle::Inner(<Token![!]>::new(span)),
382 path: Ident::new("doc", span).into(),
383 tts: vec![
384 eq(span),
385 lit,
386 ].into_iter().collect(),
387 is_sugared_doc: true,
388 pound_token: <Token![#]>::new(span),
389 bracket_token: token::Bracket(span),
390 }
Michael Layzell92639a52017-06-01 00:07:44 -0400391 }
392 )
393 ));
Alex Crichton954046c2017-05-30 21:49:42 -0700394
Michael Layzell92639a52017-06-01 00:07:44 -0400395 named!(pub parse_outer -> Self, alt!(
396 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800397 pound: punct!(#) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400398 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500399 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500400 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400401 )) >>
402 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500403 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700404
Michael Layzell92639a52017-06-01 00:07:44 -0400405 Attribute {
Alex Crichton954046c2017-05-30 21:49:42 -0700406 style: AttrStyle::Outer,
Michael Layzell92639a52017-06-01 00:07:44 -0400407 path: path,
408 tts: tts,
409 is_sugared_doc: false,
410 pound_token: pound,
411 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700412 }
Michael Layzell92639a52017-06-01 00:07:44 -0400413 })
414 )
415 |
416 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500417 call!(lit_doc_comment, Comment::Outer),
David Tolnayf800fc12017-12-27 22:08:48 -0500418 |lit| {
419 let span = lit.span;
420 Attribute {
421 style: AttrStyle::Outer,
422 path: Ident::new("doc", span).into(),
423 tts: vec![
424 eq(span),
425 lit,
426 ].into_iter().collect(),
427 is_sugared_doc: true,
428 pound_token: <Token![#]>::new(span),
429 bracket_token: token::Bracket(span),
430 }
Michael Layzell92639a52017-06-01 00:07:44 -0400431 }
432 )
433 ));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700434 }
David Tolnayb79ee962016-09-04 09:39:20 -0700435
David Tolnay201ef212018-01-01 00:09:14 -0500436 enum Comment {
437 Inner,
438 Outer,
439 }
440
441 fn lit_doc_comment(input: Cursor, style: Comment) -> PResult<TokenTree> {
Michael Layzell589a8f42017-06-02 19:47:01 -0400442 match input.literal() {
David Tolnay65729482017-12-31 16:14:50 -0500443 Some((span, lit, rest)) => {
David Tolnay201ef212018-01-01 00:09:14 -0500444 let string = lit.to_string();
445 let ok = match style {
David Tolnay61037c62018-01-05 16:21:03 -0800446 Comment::Inner => string.starts_with("//!") || string.starts_with("/*!"),
447 Comment::Outer => string.starts_with("///") || string.starts_with("/**"),
David Tolnay201ef212018-01-01 00:09:14 -0500448 };
449 if ok {
David Tolnay51382052017-12-27 13:46:21 -0500450 Ok((
David Tolnay51382052017-12-27 13:46:21 -0500451 TokenTree {
452 span: span,
David Tolnay360efd22018-01-04 23:35:26 -0800453 kind: TokenNode::Literal(Literal::string(&string)),
David Tolnay51382052017-12-27 13:46:21 -0500454 },
David Tolnayf4aa6b42017-12-31 16:40:33 -0500455 rest,
David Tolnay51382052017-12-27 13:46:21 -0500456 ))
Michael Layzell589a8f42017-06-02 19:47:01 -0400457 } else {
458 parse_error()
459 }
460 }
David Tolnay51382052017-12-27 13:46:21 -0500461 _ => parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700462 }
463 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700464}
David Tolnay87d0b442016-09-04 11:52:12 -0700465
466#[cfg(feature = "printing")]
467mod printing {
468 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500469 use quote::{ToTokens, Tokens};
David Tolnay360efd22018-01-04 23:35:26 -0800470 use proc_macro2::Literal;
David Tolnay87d0b442016-09-04 11:52:12 -0700471
472 impl ToTokens for Attribute {
473 fn to_tokens(&self, tokens: &mut Tokens) {
Arnavion44d2bf32017-04-19 02:47:55 -0700474 // If this was a sugared doc, emit it in its original form instead of `#[doc = "..."]`
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700475 if self.is_sugared_doc {
David Tolnayaaadd782018-01-06 22:58:13 -0800476 if let Some(Meta::NameValue(ref pair)) = self.interpret_meta() {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700477 if pair.ident == "doc" {
David Tolnay360efd22018-01-04 23:35:26 -0800478 if let Lit::Str(ref comment) = pair.lit {
479 tokens.append(TokenTree {
480 span: comment.span,
481 kind: TokenNode::Literal(Literal::doccomment(&comment.value())),
482 });
David Tolnay51382052017-12-27 13:46:21 -0500483 return;
David Tolnay14cbdeb2016-10-01 12:13:59 -0700484 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700485 }
David Tolnayc91dd672016-10-01 01:03:56 -0700486 }
487 }
David Tolnay14cbdeb2016-10-01 12:13:59 -0700488
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700489 self.pound_token.to_tokens(tokens);
490 if let AttrStyle::Inner(ref b) = self.style {
491 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700492 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700493 self.bracket_token.surround(tokens, |tokens| {
494 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800495 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700496 });
David Tolnay87d0b442016-09-04 11:52:12 -0700497 }
498 }
499
David Tolnayaaadd782018-01-06 22:58:13 -0800500 impl ToTokens for MetaList {
David Tolnay87d0b442016-09-04 11:52:12 -0700501 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700502 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700503 self.paren_token.surround(tokens, |tokens| {
504 self.nested.to_tokens(tokens);
505 })
David Tolnay87d0b442016-09-04 11:52:12 -0700506 }
507 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700508
Alex Crichton62a0a592017-05-22 13:58:53 -0700509 impl ToTokens for MetaNameValue {
David Tolnayb7fa2b62016-10-30 10:50:47 -0700510 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700511 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700512 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700513 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700514 }
515 }
David Tolnay87d0b442016-09-04 11:52:12 -0700516}