blob: d2ca8701a23cc669d62de870c153022c526a2f5e [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 ///
53 /// Use the [`meta_item`] method to try parsing the tokens of an attribute
54 /// into the structured representation that is used by convention across
55 /// most Rust libraries.
56 ///
57 /// [`meta_item`]: #method.meta_item
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 Tolnayaaadd782018-01-06 22:58:13 -080097 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if possible.
98 pub fn interpret_meta(&self) -> Option<Meta> {
Arnavion95f8a7a2017-04-19 03:29:56 -070099 let name = if self.path.segments.len() == 1 {
David Tolnay56080682018-01-06 14:01:52 -0800100 &self.path.segments.first().unwrap().value().ident
Arnavion95f8a7a2017-04-19 03:29:56 -0700101 } else {
102 return None;
103 };
104
Arnavionbf395bf2017-04-15 15:35:22 -0700105 if self.tts.is_empty() {
David Tolnayaaadd782018-01-06 22:58:13 -0800106 return Some(Meta::Word(*name));
Arnavionbf395bf2017-04-15 15:35:22 -0700107 }
108
David Tolnay369f0c52017-12-27 01:50:45 -0500109 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
110
111 if tts.len() == 1 {
112 if let TokenNode::Group(Delimiter::Parenthesis, ref ts) = tts[0].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700113 let tokens = ts.clone().into_iter().collect::<Vec<_>>();
114 if let Some(nested_meta_items) = list_of_nested_meta_items_from_tokens(&tokens) {
David Tolnayaaadd782018-01-06 22:58:13 -0800115 return Some(Meta::List(MetaList {
David Tolnay369f0c52017-12-27 01:50:45 -0500116 paren_token: token::Paren(tts[0].span),
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500117 ident: *name,
Alex Crichton62a0a592017-05-22 13:58:53 -0700118 nested: nested_meta_items,
119 }));
Arnavionbf395bf2017-04-15 15:35:22 -0700120 }
121 }
122 }
123
David Tolnay369f0c52017-12-27 01:50:45 -0500124 if tts.len() == 2 {
125 if let TokenNode::Op('=', Spacing::Alone) = tts[0].kind {
126 if let TokenNode::Literal(ref lit) = tts[1].kind {
David Tolnayaaadd782018-01-06 22:58:13 -0800127 return Some(Meta::NameValue(MetaNameValue {
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500128 ident: *name,
David Tolnay369f0c52017-12-27 01:50:45 -0500129 eq_token: Token![=]([tts[0].span]),
David Tolnay360efd22018-01-04 23:35:26 -0800130 lit: Lit::new(lit.clone(), tts[1].span),
Alex Crichton62a0a592017-05-22 13:58:53 -0700131 }));
Arnavionbf395bf2017-04-15 15:35:22 -0700132 }
Arnavionbf395bf2017-04-15 15:35:22 -0700133 }
134 }
135
136 None
David Tolnay02d77cc2016-10-02 09:52:08 -0700137 }
138}
139
David Tolnayaaadd782018-01-06 22:58:13 -0800140fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700141 assert!(!tts.is_empty());
142
143 match tts[0].kind {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700144 TokenNode::Literal(ref lit) => {
David Tolnay360efd22018-01-04 23:35:26 -0800145 let lit = Lit::new(lit.clone(), tts[0].span);
David Tolnayaaadd782018-01-06 22:58:13 -0800146 Some((NestedMeta::Literal(lit), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700147 }
148
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700149 TokenNode::Term(sym) => {
David Tolnayeb771d72017-12-27 22:11:06 -0500150 let ident = Ident::new(sym.as_str(), tts[0].span);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700151 if tts.len() >= 3 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700152 if let TokenNode::Op('=', Spacing::Alone) = tts[1].kind {
153 if let TokenNode::Literal(ref lit) = tts[2].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700154 let pair = MetaNameValue {
David Tolnayeb771d72017-12-27 22:11:06 -0500155 ident: Ident::new(sym.as_str(), tts[0].span),
David Tolnay98942562017-12-26 21:24:35 -0500156 eq_token: Token![=]([tts[1].span]),
David Tolnay360efd22018-01-04 23:35:26 -0800157 lit: Lit::new(lit.clone(), tts[2].span),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700158 };
David Tolnayaaadd782018-01-06 22:58:13 -0800159 return Some((Meta::NameValue(pair).into(), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700160 }
161 }
162 }
163
164 if tts.len() >= 2 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700165 if let TokenNode::Group(Delimiter::Parenthesis, ref inner_tts) = tts[1].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700166 let inner_tts = inner_tts.clone().into_iter().collect::<Vec<_>>();
167 return match list_of_nested_meta_items_from_tokens(&inner_tts) {
168 Some(nested_meta_items) => {
David Tolnayaaadd782018-01-06 22:58:13 -0800169 let list = MetaList {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700170 ident: ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500171 paren_token: token::Paren(tts[1].span),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700172 nested: nested_meta_items,
173 };
David Tolnayaaadd782018-01-06 22:58:13 -0800174 Some((Meta::List(list).into(), &tts[2..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700175 }
176
David Tolnay51382052017-12-27 13:46:21 -0500177 None => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700178 };
179 }
180 }
181
David Tolnayaaadd782018-01-06 22:58:13 -0800182 Some((Meta::Word(ident).into(), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700183 }
184
David Tolnay51382052017-12-27 13:46:21 -0500185 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700186 }
187}
188
David Tolnay51382052017-12-27 13:46:21 -0500189fn list_of_nested_meta_items_from_tokens(
190 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800191) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500192 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700193 let mut first = true;
194
195 while !tts.is_empty() {
196 let prev_comma = if first {
197 first = false;
198 None
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700199 } else if let TokenNode::Op(',', Spacing::Alone) = tts[0].kind {
David Tolnay98942562017-12-26 21:24:35 -0500200 let tok = Token![,]([tts[0].span]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700201 tts = &tts[1..];
202 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500203 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700204 }
205 Some(tok)
206 } else {
David Tolnay51382052017-12-27 13:46:21 -0500207 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700208 };
209 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
210 Some(pair) => pair,
211 None => return None,
212 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500213 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800214 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700215 }
David Tolnay56080682018-01-06 14:01:52 -0800216 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700217 tts = rest;
218 }
219
David Tolnayf2cfd722017-12-31 18:02:51 -0500220 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700221}
222
Alex Crichton62a0a592017-05-22 13:58:53 -0700223ast_enum! {
224 /// Distinguishes between Attributes that decorate items and Attributes that
David Tolnay23557142018-01-06 22:45:40 -0800225 /// are contained as statements within items.
226 ///
227 /// # Outer attributes
228 ///
229 /// - `#[repr(transparent)]`
230 /// - `/// # Example`
231 /// - `/** Please file an issue */`
232 ///
233 /// # Inner attributes
234 ///
235 /// - `#![feature(proc_macro)]`
236 /// - `//! # Example`
237 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700238 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700239 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700240 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800241 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700242 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700243}
244
Alex Crichton62a0a592017-05-22 13:58:53 -0700245ast_enum_of_structs! {
246 /// A compile-time attribute item.
David Tolnayb79ee962016-09-04 09:39:20 -0700247 ///
Alex Crichton62a0a592017-05-22 13:58:53 -0700248 /// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
David Tolnayaaadd782018-01-06 22:58:13 -0800249 pub enum Meta {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700250 /// Term meta item.
Alex Crichton62a0a592017-05-22 13:58:53 -0700251 ///
252 /// E.g. `test` as in `#[test]`
David Tolnayaaadd782018-01-06 22:58:13 -0800253 pub Word(Ident),
Clar Charrd22b5702017-03-10 15:24:56 -0500254
Alex Crichton62a0a592017-05-22 13:58:53 -0700255 /// List meta item.
256 ///
257 /// E.g. `derive(..)` as in `#[derive(..)]`
David Tolnayaaadd782018-01-06 22:58:13 -0800258 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700259 /// Name of this attribute.
260 ///
261 /// E.g. `derive` in `#[derive(..)]`
262 pub ident: Ident,
Clar Charrd22b5702017-03-10 15:24:56 -0500263
David Tolnay32954ef2017-12-26 22:43:16 -0500264 pub paren_token: token::Paren,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700265
Alex Crichton62a0a592017-05-22 13:58:53 -0700266 /// Arguments to this attribute
267 ///
268 /// E.g. `..` in `#[derive(..)]`
David Tolnayaaadd782018-01-06 22:58:13 -0800269 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700270 }),
271
272 /// Name-value meta item.
273 ///
274 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
275 pub NameValue(MetaNameValue {
276 /// Name of this attribute.
277 ///
278 /// E.g. `feature` in `#[feature = "foo"]`
279 pub ident: Ident,
280
David Tolnayf8db7ba2017-11-11 22:52:16 -0800281 pub eq_token: Token![=],
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700282
Alex Crichton62a0a592017-05-22 13:58:53 -0700283 /// Arguments to this attribute
284 ///
285 /// E.g. `"foo"` in `#[feature = "foo"]`
286 pub lit: Lit,
287 }),
288 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700289}
290
David Tolnayaaadd782018-01-06 22:58:13 -0800291impl Meta {
Arnavion95f8a7a2017-04-19 03:29:56 -0700292 /// Name of the item.
293 ///
294 /// E.g. `test` as in `#[test]`, `derive` as in `#[derive(..)]`, and
295 /// `feature` as in `#[feature = "foo"]`.
296 pub fn name(&self) -> &str {
297 match *self {
David Tolnayaaadd782018-01-06 22:58:13 -0800298 Meta::Word(ref name) => name.as_ref(),
299 Meta::NameValue(ref pair) => pair.ident.as_ref(),
300 Meta::List(ref list) => list.ident.as_ref(),
Arnavion95f8a7a2017-04-19 03:29:56 -0700301 }
302 }
David Tolnay8e661e22016-09-27 00:00:04 -0700303}
304
Alex Crichton62a0a592017-05-22 13:58:53 -0700305ast_enum_of_structs! {
306 /// Possible values inside of compile-time attribute lists.
David Tolnayb7fa2b62016-10-30 10:50:47 -0700307 ///
Alex Crichton62a0a592017-05-22 13:58:53 -0700308 /// E.g. the '..' in `#[name(..)]`.
David Tolnayaaadd782018-01-06 22:58:13 -0800309 pub enum NestedMeta {
310 /// A full `Meta`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700311 ///
David Tolnayaaadd782018-01-06 22:58:13 -0800312 /// E.g. `Copy` in `#[derive(Copy)]` would be a `Meta::Word(Ident::from("Copy"))`.
313 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500314
Alex Crichton62a0a592017-05-22 13:58:53 -0700315 /// A Rust literal.
316 ///
317 /// E.g. `"name"` in `#[rename("name")]`.
318 pub Literal(Lit),
319 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700320}
321
David Tolnay4a51dc72016-10-01 00:40:31 -0700322pub trait FilterAttrs<'a> {
323 type Ret: Iterator<Item = &'a Attribute>;
324
325 fn outer(self) -> Self::Ret;
326 fn inner(self) -> Self::Ret;
327}
328
David Tolnaydaaf7742016-10-03 11:11:43 -0700329impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500330where
331 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700332{
David Tolnay4a51dc72016-10-01 00:40:31 -0700333 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
334
335 fn outer(self) -> Self::Ret {
336 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700337 match attr.style {
338 AttrStyle::Outer => true,
339 _ => false,
340 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700341 }
342 self.into_iter().filter(is_outer)
343 }
344
345 fn inner(self) -> Self::Ret {
346 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700347 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700348 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700349 _ => false,
350 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700351 }
352 self.into_iter().filter(is_inner)
353 }
354}
355
David Tolnay86eca752016-09-04 11:26:41 -0700356#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700357pub mod parsing {
358 use super::*;
David Tolnaydfc886b2018-01-06 08:03:09 -0800359 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500360 use parse_error;
361 use synom::PResult;
David Tolnay61037c62018-01-05 16:21:03 -0800362 use proc_macro2::{Literal, Spacing, Span, TokenNode, TokenTree};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700363
David Tolnayf800fc12017-12-27 22:08:48 -0500364 fn eq(span: Span) -> TokenTree {
Alex Crichton954046c2017-05-30 21:49:42 -0700365 TokenTree {
David Tolnayf800fc12017-12-27 22:08:48 -0500366 span: span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700367 kind: TokenNode::Op('=', Spacing::Alone),
Alex Crichton954046c2017-05-30 21:49:42 -0700368 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700369 }
370
Alex Crichton954046c2017-05-30 21:49:42 -0700371 impl Attribute {
Michael Layzell92639a52017-06-01 00:07:44 -0400372 named!(pub parse_inner -> Self, alt!(
373 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800374 pound: punct!(#) >>
375 bang: punct!(!) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400376 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500377 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500378 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400379 )) >>
380 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500381 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700382
Michael Layzell92639a52017-06-01 00:07:44 -0400383 Attribute {
384 style: AttrStyle::Inner(bang),
385 path: path,
386 tts: tts,
387 is_sugared_doc: false,
388 pound_token: pound,
389 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700390 }
Michael Layzell92639a52017-06-01 00:07:44 -0400391 })
392 )
393 |
394 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500395 call!(lit_doc_comment, Comment::Inner),
David Tolnayf800fc12017-12-27 22:08:48 -0500396 |lit| {
397 let span = lit.span;
398 Attribute {
399 style: AttrStyle::Inner(<Token![!]>::new(span)),
400 path: Ident::new("doc", span).into(),
401 tts: vec![
402 eq(span),
403 lit,
404 ].into_iter().collect(),
405 is_sugared_doc: true,
406 pound_token: <Token![#]>::new(span),
407 bracket_token: token::Bracket(span),
408 }
Michael Layzell92639a52017-06-01 00:07:44 -0400409 }
410 )
411 ));
Alex Crichton954046c2017-05-30 21:49:42 -0700412
Michael Layzell92639a52017-06-01 00:07:44 -0400413 named!(pub parse_outer -> Self, alt!(
414 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800415 pound: punct!(#) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400416 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500417 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500418 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400419 )) >>
420 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500421 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700422
Michael Layzell92639a52017-06-01 00:07:44 -0400423 Attribute {
Alex Crichton954046c2017-05-30 21:49:42 -0700424 style: AttrStyle::Outer,
Michael Layzell92639a52017-06-01 00:07:44 -0400425 path: path,
426 tts: tts,
427 is_sugared_doc: false,
428 pound_token: pound,
429 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700430 }
Michael Layzell92639a52017-06-01 00:07:44 -0400431 })
432 )
433 |
434 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500435 call!(lit_doc_comment, Comment::Outer),
David Tolnayf800fc12017-12-27 22:08:48 -0500436 |lit| {
437 let span = lit.span;
438 Attribute {
439 style: AttrStyle::Outer,
440 path: Ident::new("doc", span).into(),
441 tts: vec![
442 eq(span),
443 lit,
444 ].into_iter().collect(),
445 is_sugared_doc: true,
446 pound_token: <Token![#]>::new(span),
447 bracket_token: token::Bracket(span),
448 }
Michael Layzell92639a52017-06-01 00:07:44 -0400449 }
450 )
451 ));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700452 }
David Tolnayb79ee962016-09-04 09:39:20 -0700453
David Tolnay201ef212018-01-01 00:09:14 -0500454 enum Comment {
455 Inner,
456 Outer,
457 }
458
459 fn lit_doc_comment(input: Cursor, style: Comment) -> PResult<TokenTree> {
Michael Layzell589a8f42017-06-02 19:47:01 -0400460 match input.literal() {
David Tolnay65729482017-12-31 16:14:50 -0500461 Some((span, lit, rest)) => {
David Tolnay201ef212018-01-01 00:09:14 -0500462 let string = lit.to_string();
463 let ok = match style {
David Tolnay61037c62018-01-05 16:21:03 -0800464 Comment::Inner => string.starts_with("//!") || string.starts_with("/*!"),
465 Comment::Outer => string.starts_with("///") || string.starts_with("/**"),
David Tolnay201ef212018-01-01 00:09:14 -0500466 };
467 if ok {
David Tolnay51382052017-12-27 13:46:21 -0500468 Ok((
David Tolnay51382052017-12-27 13:46:21 -0500469 TokenTree {
470 span: span,
David Tolnay360efd22018-01-04 23:35:26 -0800471 kind: TokenNode::Literal(Literal::string(&string)),
David Tolnay51382052017-12-27 13:46:21 -0500472 },
David Tolnayf4aa6b42017-12-31 16:40:33 -0500473 rest,
David Tolnay51382052017-12-27 13:46:21 -0500474 ))
Michael Layzell589a8f42017-06-02 19:47:01 -0400475 } else {
476 parse_error()
477 }
478 }
David Tolnay51382052017-12-27 13:46:21 -0500479 _ => parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700480 }
481 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700482}
David Tolnay87d0b442016-09-04 11:52:12 -0700483
484#[cfg(feature = "printing")]
485mod printing {
486 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500487 use quote::{ToTokens, Tokens};
David Tolnay360efd22018-01-04 23:35:26 -0800488 use proc_macro2::Literal;
David Tolnay87d0b442016-09-04 11:52:12 -0700489
490 impl ToTokens for Attribute {
491 fn to_tokens(&self, tokens: &mut Tokens) {
Arnavion44d2bf32017-04-19 02:47:55 -0700492 // If this was a sugared doc, emit it in its original form instead of `#[doc = "..."]`
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700493 if self.is_sugared_doc {
David Tolnayaaadd782018-01-06 22:58:13 -0800494 if let Some(Meta::NameValue(ref pair)) = self.interpret_meta() {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700495 if pair.ident == "doc" {
David Tolnay360efd22018-01-04 23:35:26 -0800496 if let Lit::Str(ref comment) = pair.lit {
497 tokens.append(TokenTree {
498 span: comment.span,
499 kind: TokenNode::Literal(Literal::doccomment(&comment.value())),
500 });
David Tolnay51382052017-12-27 13:46:21 -0500501 return;
David Tolnay14cbdeb2016-10-01 12:13:59 -0700502 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700503 }
David Tolnayc91dd672016-10-01 01:03:56 -0700504 }
505 }
David Tolnay14cbdeb2016-10-01 12:13:59 -0700506
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700507 self.pound_token.to_tokens(tokens);
508 if let AttrStyle::Inner(ref b) = self.style {
509 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700510 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700511 self.bracket_token.surround(tokens, |tokens| {
512 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800513 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700514 });
David Tolnay87d0b442016-09-04 11:52:12 -0700515 }
516 }
517
David Tolnayaaadd782018-01-06 22:58:13 -0800518 impl ToTokens for MetaList {
David Tolnay87d0b442016-09-04 11:52:12 -0700519 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700520 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700521 self.paren_token.surround(tokens, |tokens| {
522 self.nested.to_tokens(tokens);
523 })
David Tolnay87d0b442016-09-04 11:52:12 -0700524 }
525 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700526
Alex Crichton62a0a592017-05-22 13:58:53 -0700527 impl ToTokens for MetaNameValue {
David Tolnayb7fa2b62016-10-30 10:50:47 -0700528 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700529 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700530 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700531 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700532 }
533 }
David Tolnay87d0b442016-09-04 11:52:12 -0700534}