blob: b63b302908b831d0fbf5476d6a2ff3d46dfc3676 [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
Alex Crichton9a4dca22018-03-28 06:32:19 -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
42 /// attributes that have `is_sugared_doc` set to true, as this is how they
43 /// are processed by the compiler and by `macro_rules!` macros.
44 ///
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 pub is_sugared_doc: bool,
68 }
David Tolnayb79ee962016-09-04 09:39:20 -070069}
70
David Tolnay9c76bcb2017-12-26 23:14:59 -050071#[cfg(feature = "extra-traits")]
72impl Eq for Attribute {}
73
74#[cfg(feature = "extra-traits")]
75impl PartialEq for Attribute {
76 fn eq(&self, other: &Self) -> bool {
David Tolnay51382052017-12-27 13:46:21 -050077 self.style == other.style && self.pound_token == other.pound_token
78 && self.bracket_token == other.bracket_token && self.path == other.path
David Tolnay369f0c52017-12-27 01:50:45 -050079 && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts)
David Tolnay9c76bcb2017-12-26 23:14:59 -050080 && self.is_sugared_doc == other.is_sugared_doc
81 }
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 self.is_sugared_doc.hash(state);
96 }
97}
98
David Tolnay02d77cc2016-10-02 09:52:08 -070099impl Attribute {
David Tolnay068120a2018-01-06 23:17:22 -0800100 /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if
101 /// possible.
David Tolnayaaadd782018-01-06 22:58:13 -0800102 pub fn interpret_meta(&self) -> Option<Meta> {
Arnavion95f8a7a2017-04-19 03:29:56 -0700103 let name = if self.path.segments.len() == 1 {
David Tolnay56080682018-01-06 14:01:52 -0800104 &self.path.segments.first().unwrap().value().ident
Arnavion95f8a7a2017-04-19 03:29:56 -0700105 } else {
106 return None;
107 };
108
Arnavionbf395bf2017-04-15 15:35:22 -0700109 if self.tts.is_empty() {
David Tolnayaaadd782018-01-06 22:58:13 -0800110 return Some(Meta::Word(*name));
Arnavionbf395bf2017-04-15 15:35:22 -0700111 }
112
David Tolnay369f0c52017-12-27 01:50:45 -0500113 let tts = self.tts.clone().into_iter().collect::<Vec<_>>();
114
115 if tts.len() == 1 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700116 if let Some(meta) = Attribute::extract_meta_list(*name, &tts[0]) {
117 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700118 }
119 }
120
David Tolnay369f0c52017-12-27 01:50:45 -0500121 if tts.len() == 2 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700122 if let Some(meta) = Attribute::extract_name_value(*name, &tts[0], &tts[1]) {
123 return Some(meta);
Arnavionbf395bf2017-04-15 15:35:22 -0700124 }
125 }
126
127 None
David Tolnay02d77cc2016-10-02 09:52:08 -0700128 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700129
130 fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> {
131 let g = match *tt {
132 TokenTree::Group(ref g) => g,
133 _ => return None,
134 };
135 if g.delimiter() != Delimiter::Parenthesis {
David Tolnay94d2b792018-04-29 12:26:10 -0700136 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700137 }
138 let tokens = g.stream().clone().into_iter().collect::<Vec<_>>();
139 let nested = match list_of_nested_meta_items_from_tokens(&tokens) {
140 Some(n) => n,
141 None => return None,
142 };
143 Some(Meta::List(MetaList {
144 paren_token: token::Paren(g.span()),
145 ident: ident,
146 nested: nested,
147 }))
148 }
149
150 fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> {
151 let a = match *a {
152 TokenTree::Op(ref o) => o,
153 _ => return None,
154 };
155 if a.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700156 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700157 }
158 if a.op() != '=' {
David Tolnay94d2b792018-04-29 12:26:10 -0700159 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700160 }
161
162 match *b {
163 TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => {
164 Some(Meta::NameValue(MetaNameValue {
165 ident: ident,
166 eq_token: Token![=]([a.span()]),
167 lit: Lit::new(l.clone()),
168 }))
169 }
David Tolnay94d2b792018-04-29 12:26:10 -0700170 TokenTree::Term(ref term) => match term.as_str() {
171 v @ "true" | v @ "false" => Some(Meta::NameValue(MetaNameValue {
172 ident: ident,
173 eq_token: Token![=]([a.span()]),
174 lit: Lit::Bool(LitBool {
175 value: v == "true",
176 span: b.span(),
177 }),
178 })),
179 _ => None,
180 },
Alex Crichton9a4dca22018-03-28 06:32:19 -0700181 _ => None,
182 }
183 }
David Tolnay02d77cc2016-10-02 09:52:08 -0700184}
185
David Tolnayaaadd782018-01-06 22:58:13 -0800186fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700187 assert!(!tts.is_empty());
188
Alex Crichton9a4dca22018-03-28 06:32:19 -0700189 match tts[0] {
190 TokenTree::Literal(ref lit) => {
David Tolnay7037c9b2018-01-23 09:34:09 -0800191 if lit.to_string().starts_with('/') {
192 None
193 } else {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700194 let lit = Lit::new(lit.clone());
David Tolnay7037c9b2018-01-23 09:34:09 -0800195 Some((NestedMeta::Literal(lit), &tts[1..]))
196 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700197 }
198
Alex Crichton9a4dca22018-03-28 06:32:19 -0700199 TokenTree::Term(sym) => {
200 let ident = Ident::new(sym.as_str(), sym.span());
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700201 if tts.len() >= 3 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700202 if let Some(meta) = Attribute::extract_name_value(ident, &tts[1], &tts[2]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700203 return Some((NestedMeta::Meta(meta), &tts[3..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700204 }
205 }
206
207 if tts.len() >= 2 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700208 if let Some(meta) = Attribute::extract_meta_list(ident, &tts[1]) {
David Tolnay94d2b792018-04-29 12:26:10 -0700209 return Some((NestedMeta::Meta(meta), &tts[2..]));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700210 }
211 }
212
David Tolnayaaadd782018-01-06 22:58:13 -0800213 Some((Meta::Word(ident).into(), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700214 }
215
David Tolnay51382052017-12-27 13:46:21 -0500216 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700217 }
218}
219
David Tolnay51382052017-12-27 13:46:21 -0500220fn list_of_nested_meta_items_from_tokens(
221 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800222) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500223 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700224 let mut first = true;
225
226 while !tts.is_empty() {
227 let prev_comma = if first {
228 first = false;
229 None
Alex Crichton9a4dca22018-03-28 06:32:19 -0700230 } else if let TokenTree::Op(ref op) = tts[0] {
231 if op.spacing() != Spacing::Alone {
David Tolnay94d2b792018-04-29 12:26:10 -0700232 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700233 }
234 if op.op() != ',' {
David Tolnay94d2b792018-04-29 12:26:10 -0700235 return None;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700236 }
237 let tok = Token![,]([op.span()]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700238 tts = &tts[1..];
239 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500240 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700241 }
242 Some(tok)
243 } else {
David Tolnay51382052017-12-27 13:46:21 -0500244 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700245 };
246 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
247 Some(pair) => pair,
248 None => return None,
249 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500250 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800251 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700252 }
David Tolnay56080682018-01-06 14:01:52 -0800253 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700254 tts = rest;
255 }
256
David Tolnayf2cfd722017-12-31 18:02:51 -0500257 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700258}
259
Alex Crichton62a0a592017-05-22 13:58:53 -0700260ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800261 /// Distinguishes between attributes that decorate an item and attributes
262 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800263 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800264 /// *This type is available if Syn is built with the `"derive"` or `"full"`
265 /// feature.*
266 ///
David Tolnay23557142018-01-06 22:45:40 -0800267 /// # Outer attributes
268 ///
269 /// - `#[repr(transparent)]`
270 /// - `/// # Example`
271 /// - `/** Please file an issue */`
272 ///
273 /// # Inner attributes
274 ///
275 /// - `#![feature(proc_macro)]`
276 /// - `//! # Example`
277 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700278 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700279 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700280 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800281 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700282 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700283}
284
Alex Crichton62a0a592017-05-22 13:58:53 -0700285ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800286 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700287 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800288 /// *This type is available if Syn is built with the `"derive"` or `"full"`
289 /// feature.*
290 ///
David Tolnay068120a2018-01-06 23:17:22 -0800291 /// ## Word
292 ///
293 /// A meta word is like the `test` in `#[test]`.
294 ///
295 /// ## List
296 ///
297 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
298 ///
299 /// ## NameValue
300 ///
301 /// A name-value meta is like the `path = "..."` in `#[path =
302 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800303 ///
304 /// # Syntax tree enum
305 ///
306 /// This type is a [syntax tree enum].
307 ///
308 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800309 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800310 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800311 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800312 ///
313 /// *This type is available if Syn is built with the `"derive"` or
314 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800315 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700316 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500317 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800318 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700319 }),
David Tolnay068120a2018-01-06 23:17:22 -0800320 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800321 ///
322 /// *This type is available if Syn is built with the `"derive"` or
323 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700324 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700325 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800326 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700327 pub lit: Lit,
328 }),
329 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700330}
331
David Tolnayaaadd782018-01-06 22:58:13 -0800332impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800333 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700334 ///
David Tolnay068120a2018-01-06 23:17:22 -0800335 /// For example this would return the `test` in `#[test]`, the `derive` in
336 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
337 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700338 match *self {
David Tolnay068120a2018-01-06 23:17:22 -0800339 Meta::Word(ref meta) => *meta,
340 Meta::List(ref meta) => meta.ident,
341 Meta::NameValue(ref meta) => meta.ident,
Arnavion95f8a7a2017-04-19 03:29:56 -0700342 }
343 }
David Tolnay8e661e22016-09-27 00:00:04 -0700344}
345
Alex Crichton62a0a592017-05-22 13:58:53 -0700346ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800347 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800348 ///
349 /// *This type is available if Syn is built with the `"derive"` or `"full"`
350 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800351 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800352 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
353 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800354 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500355
David Tolnay068120a2018-01-06 23:17:22 -0800356 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700357 pub Literal(Lit),
358 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700359}
360
David Tolnay4a51dc72016-10-01 00:40:31 -0700361pub trait FilterAttrs<'a> {
362 type Ret: Iterator<Item = &'a Attribute>;
363
364 fn outer(self) -> Self::Ret;
365 fn inner(self) -> Self::Ret;
366}
367
David Tolnaydaaf7742016-10-03 11:11:43 -0700368impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500369where
370 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700371{
David Tolnay4a51dc72016-10-01 00:40:31 -0700372 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
373
374 fn outer(self) -> Self::Ret {
375 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700376 match attr.style {
377 AttrStyle::Outer => true,
378 _ => false,
379 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700380 }
381 self.into_iter().filter(is_outer)
382 }
383
384 fn inner(self) -> Self::Ret {
385 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700386 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700387 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700388 _ => false,
389 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700390 }
391 self.into_iter().filter(is_inner)
392 }
393}
394
David Tolnay86eca752016-09-04 11:26:41 -0700395#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700396pub mod parsing {
397 use super::*;
David Tolnaydfc886b2018-01-06 08:03:09 -0800398 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500399 use parse_error;
David Tolnay94d2b792018-04-29 12:26:10 -0700400 use proc_macro2::{Literal, Op, Spacing, Span, TokenTree};
David Tolnay203557a2017-12-27 23:59:33 -0500401 use synom::PResult;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700402
David Tolnayf800fc12017-12-27 22:08:48 -0500403 fn eq(span: Span) -> TokenTree {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700404 let mut op = Op::new('=', Spacing::Alone);
405 op.set_span(span);
406 op.into()
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700407 }
408
Alex Crichton954046c2017-05-30 21:49:42 -0700409 impl Attribute {
Michael Layzell92639a52017-06-01 00:07:44 -0400410 named!(pub parse_inner -> Self, alt!(
411 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800412 pound: punct!(#) >>
413 bang: punct!(!) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400414 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500415 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500416 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400417 )) >>
418 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500419 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700420
Michael Layzell92639a52017-06-01 00:07:44 -0400421 Attribute {
422 style: AttrStyle::Inner(bang),
423 path: path,
424 tts: tts,
425 is_sugared_doc: false,
426 pound_token: pound,
427 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700428 }
Michael Layzell92639a52017-06-01 00:07:44 -0400429 })
430 )
431 |
432 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500433 call!(lit_doc_comment, Comment::Inner),
David Tolnayf800fc12017-12-27 22:08:48 -0500434 |lit| {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700435 let span = lit.span();
David Tolnayf800fc12017-12-27 22:08:48 -0500436 Attribute {
437 style: AttrStyle::Inner(<Token![!]>::new(span)),
438 path: Ident::new("doc", span).into(),
439 tts: vec![
440 eq(span),
441 lit,
442 ].into_iter().collect(),
443 is_sugared_doc: true,
444 pound_token: <Token![#]>::new(span),
445 bracket_token: token::Bracket(span),
446 }
Michael Layzell92639a52017-06-01 00:07:44 -0400447 }
448 )
449 ));
Alex Crichton954046c2017-05-30 21:49:42 -0700450
Michael Layzell92639a52017-06-01 00:07:44 -0400451 named!(pub parse_outer -> Self, alt!(
452 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800453 pound: punct!(#) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400454 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500455 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500456 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400457 )) >>
458 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500459 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700460
Michael Layzell92639a52017-06-01 00:07:44 -0400461 Attribute {
Alex Crichton954046c2017-05-30 21:49:42 -0700462 style: AttrStyle::Outer,
Michael Layzell92639a52017-06-01 00:07:44 -0400463 path: path,
464 tts: tts,
465 is_sugared_doc: false,
466 pound_token: pound,
467 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700468 }
Michael Layzell92639a52017-06-01 00:07:44 -0400469 })
470 )
471 |
472 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500473 call!(lit_doc_comment, Comment::Outer),
David Tolnayf800fc12017-12-27 22:08:48 -0500474 |lit| {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700475 let span = lit.span();
David Tolnayf800fc12017-12-27 22:08:48 -0500476 Attribute {
477 style: AttrStyle::Outer,
478 path: Ident::new("doc", span).into(),
479 tts: vec![
480 eq(span),
481 lit,
482 ].into_iter().collect(),
483 is_sugared_doc: true,
484 pound_token: <Token![#]>::new(span),
485 bracket_token: token::Bracket(span),
486 }
Michael Layzell92639a52017-06-01 00:07:44 -0400487 }
488 )
489 ));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700490 }
David Tolnayb79ee962016-09-04 09:39:20 -0700491
David Tolnay201ef212018-01-01 00:09:14 -0500492 enum Comment {
493 Inner,
494 Outer,
495 }
496
497 fn lit_doc_comment(input: Cursor, style: Comment) -> PResult<TokenTree> {
Michael Layzell589a8f42017-06-02 19:47:01 -0400498 match input.literal() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700499 Some((lit, rest)) => {
David Tolnay201ef212018-01-01 00:09:14 -0500500 let string = lit.to_string();
501 let ok = match style {
David Tolnay61037c62018-01-05 16:21:03 -0800502 Comment::Inner => string.starts_with("//!") || string.starts_with("/*!"),
503 Comment::Outer => string.starts_with("///") || string.starts_with("/**"),
David Tolnay201ef212018-01-01 00:09:14 -0500504 };
505 if ok {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700506 let mut new = Literal::string(&string);
507 new.set_span(lit.span());
508 Ok((new.into(), rest))
Michael Layzell589a8f42017-06-02 19:47:01 -0400509 } else {
510 parse_error()
511 }
512 }
David Tolnay51382052017-12-27 13:46:21 -0500513 _ => parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700514 }
515 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700516}
David Tolnay87d0b442016-09-04 11:52:12 -0700517
518#[cfg(feature = "printing")]
519mod printing {
520 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500521 use quote::{ToTokens, Tokens};
David Tolnay87d0b442016-09-04 11:52:12 -0700522
523 impl ToTokens for Attribute {
524 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700525 self.pound_token.to_tokens(tokens);
526 if let AttrStyle::Inner(ref b) = self.style {
527 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700528 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700529 self.bracket_token.surround(tokens, |tokens| {
530 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800531 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700532 });
David Tolnay87d0b442016-09-04 11:52:12 -0700533 }
534 }
535
David Tolnayaaadd782018-01-06 22:58:13 -0800536 impl ToTokens for MetaList {
David Tolnay87d0b442016-09-04 11:52:12 -0700537 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700538 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700539 self.paren_token.surround(tokens, |tokens| {
540 self.nested.to_tokens(tokens);
541 })
David Tolnay87d0b442016-09-04 11:52:12 -0700542 }
543 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700544
Alex Crichton62a0a592017-05-22 13:58:53 -0700545 impl ToTokens for MetaNameValue {
David Tolnayb7fa2b62016-10-30 10:50:47 -0700546 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700547 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700548 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700549 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700550 }
551 }
David Tolnay87d0b442016-09-04 11:52:12 -0700552}