blob: 3c9e625a4e54a7cf00ba0dcf6fa58ec8f0e067f6 [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 ///
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 {
116 if let TokenNode::Group(Delimiter::Parenthesis, ref ts) = tts[0].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700117 let tokens = ts.clone().into_iter().collect::<Vec<_>>();
118 if let Some(nested_meta_items) = list_of_nested_meta_items_from_tokens(&tokens) {
David Tolnayaaadd782018-01-06 22:58:13 -0800119 return Some(Meta::List(MetaList {
David Tolnay369f0c52017-12-27 01:50:45 -0500120 paren_token: token::Paren(tts[0].span),
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500121 ident: *name,
Alex Crichton62a0a592017-05-22 13:58:53 -0700122 nested: nested_meta_items,
123 }));
Arnavionbf395bf2017-04-15 15:35:22 -0700124 }
125 }
126 }
127
David Tolnay369f0c52017-12-27 01:50:45 -0500128 if tts.len() == 2 {
129 if let TokenNode::Op('=', Spacing::Alone) = tts[0].kind {
130 if let TokenNode::Literal(ref lit) = tts[1].kind {
David Tolnayaaadd782018-01-06 22:58:13 -0800131 return Some(Meta::NameValue(MetaNameValue {
David Tolnaybb4ca9f2017-12-26 12:28:58 -0500132 ident: *name,
David Tolnay369f0c52017-12-27 01:50:45 -0500133 eq_token: Token![=]([tts[0].span]),
David Tolnay360efd22018-01-04 23:35:26 -0800134 lit: Lit::new(lit.clone(), tts[1].span),
Alex Crichton62a0a592017-05-22 13:58:53 -0700135 }));
Bastien Orivel9ea50332018-01-23 17:39:32 +0100136 } else if let TokenNode::Term(ref term) = tts[1].kind {
137 match term.as_str() {
138 v @ "true" | v @ "false" => {
139 return Some(Meta::NameValue(MetaNameValue {
140 ident: *name,
141 eq_token: Token![=]([tts[0].span]),
142 lit: Lit::Bool(LitBool { value: v == "true", span: tts[1].span }),
143 }));
144 },
145 _ => {}
146 }
Arnavionbf395bf2017-04-15 15:35:22 -0700147 }
Arnavionbf395bf2017-04-15 15:35:22 -0700148 }
149 }
150
151 None
David Tolnay02d77cc2016-10-02 09:52:08 -0700152 }
153}
154
David Tolnayaaadd782018-01-06 22:58:13 -0800155fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700156 assert!(!tts.is_empty());
157
158 match tts[0].kind {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700159 TokenNode::Literal(ref lit) => {
David Tolnay360efd22018-01-04 23:35:26 -0800160 let lit = Lit::new(lit.clone(), tts[0].span);
David Tolnayaaadd782018-01-06 22:58:13 -0800161 Some((NestedMeta::Literal(lit), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700162 }
163
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700164 TokenNode::Term(sym) => {
David Tolnayeb771d72017-12-27 22:11:06 -0500165 let ident = Ident::new(sym.as_str(), tts[0].span);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700166 if tts.len() >= 3 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700167 if let TokenNode::Op('=', Spacing::Alone) = tts[1].kind {
168 if let TokenNode::Literal(ref lit) = tts[2].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700169 let pair = MetaNameValue {
David Tolnayeb771d72017-12-27 22:11:06 -0500170 ident: Ident::new(sym.as_str(), tts[0].span),
David Tolnay98942562017-12-26 21:24:35 -0500171 eq_token: Token![=]([tts[1].span]),
David Tolnay360efd22018-01-04 23:35:26 -0800172 lit: Lit::new(lit.clone(), tts[2].span),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700173 };
David Tolnayaaadd782018-01-06 22:58:13 -0800174 return Some((Meta::NameValue(pair).into(), &tts[3..]));
Bastien Orivel9ea50332018-01-23 17:39:32 +0100175 } else if let TokenNode::Term(ref term) = tts[2].kind {
176 match term.as_str() {
177 v @ "true" | v @ "false" => {
178 let pair = MetaNameValue {
179 ident: Ident::new(sym.as_str(), tts[0].span),
180 eq_token: Token![=]([tts[1].span]),
181 lit: Lit::Bool(LitBool { value: v == "true", span: tts[2].span }),
182 };
183 return Some((Meta::NameValue(pair).into(), &tts[3..]));
184 },
185 _ => {}
186 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700187 }
188 }
189 }
190
191 if tts.len() >= 2 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700192 if let TokenNode::Group(Delimiter::Parenthesis, ref inner_tts) = tts[1].kind {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700193 let inner_tts = inner_tts.clone().into_iter().collect::<Vec<_>>();
194 return match list_of_nested_meta_items_from_tokens(&inner_tts) {
195 Some(nested_meta_items) => {
David Tolnayaaadd782018-01-06 22:58:13 -0800196 let list = MetaList {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700197 ident: ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500198 paren_token: token::Paren(tts[1].span),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700199 nested: nested_meta_items,
200 };
David Tolnayaaadd782018-01-06 22:58:13 -0800201 Some((Meta::List(list).into(), &tts[2..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700202 }
203
David Tolnay51382052017-12-27 13:46:21 -0500204 None => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700205 };
206 }
207 }
208
David Tolnayaaadd782018-01-06 22:58:13 -0800209 Some((Meta::Word(ident).into(), &tts[1..]))
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700210 }
211
David Tolnay51382052017-12-27 13:46:21 -0500212 _ => None,
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700213 }
214}
215
David Tolnay51382052017-12-27 13:46:21 -0500216fn list_of_nested_meta_items_from_tokens(
217 mut tts: &[TokenTree],
David Tolnayaaadd782018-01-06 22:58:13 -0800218) -> Option<Punctuated<NestedMeta, Token![,]>> {
David Tolnayf2cfd722017-12-31 18:02:51 -0500219 let mut nested_meta_items = Punctuated::new();
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700220 let mut first = true;
221
222 while !tts.is_empty() {
223 let prev_comma = if first {
224 first = false;
225 None
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700226 } else if let TokenNode::Op(',', Spacing::Alone) = tts[0].kind {
David Tolnay98942562017-12-26 21:24:35 -0500227 let tok = Token![,]([tts[0].span]);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700228 tts = &tts[1..];
229 if tts.is_empty() {
David Tolnay51382052017-12-27 13:46:21 -0500230 break;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700231 }
232 Some(tok)
233 } else {
David Tolnay51382052017-12-27 13:46:21 -0500234 return None;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700235 };
236 let (nested, rest) = match nested_meta_item_from_tokens(tts) {
237 Some(pair) => pair,
238 None => return None,
239 };
David Tolnay660fd1f2017-12-31 01:52:57 -0500240 if let Some(comma) = prev_comma {
David Tolnaya0834b42018-01-01 21:30:02 -0800241 nested_meta_items.push_punct(comma);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700242 }
David Tolnay56080682018-01-06 14:01:52 -0800243 nested_meta_items.push_value(nested);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700244 tts = rest;
245 }
246
David Tolnayf2cfd722017-12-31 18:02:51 -0500247 Some(nested_meta_items)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700248}
249
Alex Crichton62a0a592017-05-22 13:58:53 -0700250ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800251 /// Distinguishes between attributes that decorate an item and attributes
252 /// that are contained within an item.
David Tolnay23557142018-01-06 22:45:40 -0800253 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800254 /// *This type is available if Syn is built with the `"derive"` or `"full"`
255 /// feature.*
256 ///
David Tolnay23557142018-01-06 22:45:40 -0800257 /// # Outer attributes
258 ///
259 /// - `#[repr(transparent)]`
260 /// - `/// # Example`
261 /// - `/** Please file an issue */`
262 ///
263 /// # Inner attributes
264 ///
265 /// - `#![feature(proc_macro)]`
266 /// - `//! # Example`
267 /// - `/*! Please file an issue */`
Alex Crichton2e0229c2017-05-23 09:34:50 -0700268 #[cfg_attr(feature = "clone-impls", derive(Copy))]
Alex Crichton62a0a592017-05-22 13:58:53 -0700269 pub enum AttrStyle {
Alex Crichton62a0a592017-05-22 13:58:53 -0700270 Outer,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800271 Inner(Token![!]),
Alex Crichton62a0a592017-05-22 13:58:53 -0700272 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700273}
274
Alex Crichton62a0a592017-05-22 13:58:53 -0700275ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800276 /// Content of a compile-time structured attribute.
David Tolnayb79ee962016-09-04 09:39:20 -0700277 ///
David Tolnay461d98e2018-01-07 11:07:19 -0800278 /// *This type is available if Syn is built with the `"derive"` or `"full"`
279 /// feature.*
280 ///
David Tolnay068120a2018-01-06 23:17:22 -0800281 /// ## Word
282 ///
283 /// A meta word is like the `test` in `#[test]`.
284 ///
285 /// ## List
286 ///
287 /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
288 ///
289 /// ## NameValue
290 ///
291 /// A name-value meta is like the `path = "..."` in `#[path =
292 /// "sys/windows.rs"]`.
David Tolnay614a0142018-01-07 10:25:43 -0800293 ///
294 /// # Syntax tree enum
295 ///
296 /// This type is a [syntax tree enum].
297 ///
298 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnayaaadd782018-01-06 22:58:13 -0800299 pub enum Meta {
David Tolnayaaadd782018-01-06 22:58:13 -0800300 pub Word(Ident),
David Tolnay068120a2018-01-06 23:17:22 -0800301 /// A structured list within an attribute, like `derive(Copy, Clone)`.
David Tolnay461d98e2018-01-07 11:07:19 -0800302 ///
303 /// *This type is available if Syn is built with the `"derive"` or
304 /// `"full"` feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800305 pub List(MetaList {
Alex Crichton62a0a592017-05-22 13:58:53 -0700306 pub ident: Ident,
David Tolnay32954ef2017-12-26 22:43:16 -0500307 pub paren_token: token::Paren,
David Tolnayaaadd782018-01-06 22:58:13 -0800308 pub nested: Punctuated<NestedMeta, Token![,]>,
Alex Crichton62a0a592017-05-22 13:58:53 -0700309 }),
David Tolnay068120a2018-01-06 23:17:22 -0800310 /// A name-value pair within an attribute, like `feature = "nightly"`.
David Tolnay461d98e2018-01-07 11:07:19 -0800311 ///
312 /// *This type is available if Syn is built with the `"derive"` or
313 /// `"full"` feature.*
Alex Crichton62a0a592017-05-22 13:58:53 -0700314 pub NameValue(MetaNameValue {
Alex Crichton62a0a592017-05-22 13:58:53 -0700315 pub ident: Ident,
David Tolnayf8db7ba2017-11-11 22:52:16 -0800316 pub eq_token: Token![=],
Alex Crichton62a0a592017-05-22 13:58:53 -0700317 pub lit: Lit,
318 }),
319 }
Arnavion95f8a7a2017-04-19 03:29:56 -0700320}
321
David Tolnayaaadd782018-01-06 22:58:13 -0800322impl Meta {
David Tolnay068120a2018-01-06 23:17:22 -0800323 /// Returns the identifier that begins this structured meta item.
Arnavion95f8a7a2017-04-19 03:29:56 -0700324 ///
David Tolnay068120a2018-01-06 23:17:22 -0800325 /// For example this would return the `test` in `#[test]`, the `derive` in
326 /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`.
327 pub fn name(&self) -> Ident {
Arnavion95f8a7a2017-04-19 03:29:56 -0700328 match *self {
David Tolnay068120a2018-01-06 23:17:22 -0800329 Meta::Word(ref meta) => *meta,
330 Meta::List(ref meta) => meta.ident,
331 Meta::NameValue(ref meta) => meta.ident,
Arnavion95f8a7a2017-04-19 03:29:56 -0700332 }
333 }
David Tolnay8e661e22016-09-27 00:00:04 -0700334}
335
Alex Crichton62a0a592017-05-22 13:58:53 -0700336ast_enum_of_structs! {
David Tolnay068120a2018-01-06 23:17:22 -0800337 /// Element of a compile-time attribute list.
David Tolnay461d98e2018-01-07 11:07:19 -0800338 ///
339 /// *This type is available if Syn is built with the `"derive"` or `"full"`
340 /// feature.*
David Tolnayaaadd782018-01-06 22:58:13 -0800341 pub enum NestedMeta {
David Tolnay068120a2018-01-06 23:17:22 -0800342 /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which
343 /// would be a nested `Meta::Word`.
David Tolnayaaadd782018-01-06 22:58:13 -0800344 pub Meta(Meta),
Clar Charrd22b5702017-03-10 15:24:56 -0500345
David Tolnay068120a2018-01-06 23:17:22 -0800346 /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`.
Alex Crichton62a0a592017-05-22 13:58:53 -0700347 pub Literal(Lit),
348 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700349}
350
David Tolnay4a51dc72016-10-01 00:40:31 -0700351pub trait FilterAttrs<'a> {
352 type Ret: Iterator<Item = &'a Attribute>;
353
354 fn outer(self) -> Self::Ret;
355 fn inner(self) -> Self::Ret;
356}
357
David Tolnaydaaf7742016-10-03 11:11:43 -0700358impl<'a, T> FilterAttrs<'a> for T
David Tolnay51382052017-12-27 13:46:21 -0500359where
360 T: IntoIterator<Item = &'a Attribute>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700361{
David Tolnay4a51dc72016-10-01 00:40:31 -0700362 type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;
363
364 fn outer(self) -> Self::Ret {
365 fn is_outer(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700366 match attr.style {
367 AttrStyle::Outer => true,
368 _ => false,
369 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700370 }
371 self.into_iter().filter(is_outer)
372 }
373
374 fn inner(self) -> Self::Ret {
375 fn is_inner(attr: &&Attribute) -> bool {
Alex Crichton2e0229c2017-05-23 09:34:50 -0700376 match attr.style {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700377 AttrStyle::Inner(_) => true,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700378 _ => false,
379 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700380 }
381 self.into_iter().filter(is_inner)
382 }
383}
384
David Tolnay86eca752016-09-04 11:26:41 -0700385#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700386pub mod parsing {
387 use super::*;
David Tolnaydfc886b2018-01-06 08:03:09 -0800388 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500389 use parse_error;
390 use synom::PResult;
David Tolnay61037c62018-01-05 16:21:03 -0800391 use proc_macro2::{Literal, Spacing, Span, TokenNode, TokenTree};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700392
David Tolnayf800fc12017-12-27 22:08:48 -0500393 fn eq(span: Span) -> TokenTree {
Alex Crichton954046c2017-05-30 21:49:42 -0700394 TokenTree {
David Tolnayf800fc12017-12-27 22:08:48 -0500395 span: span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700396 kind: TokenNode::Op('=', Spacing::Alone),
Alex Crichton954046c2017-05-30 21:49:42 -0700397 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700398 }
399
Alex Crichton954046c2017-05-30 21:49:42 -0700400 impl Attribute {
Michael Layzell92639a52017-06-01 00:07:44 -0400401 named!(pub parse_inner -> Self, alt!(
402 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800403 pound: punct!(#) >>
404 bang: punct!(!) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400405 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500406 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500407 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400408 )) >>
409 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500410 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700411
Michael Layzell92639a52017-06-01 00:07:44 -0400412 Attribute {
413 style: AttrStyle::Inner(bang),
414 path: path,
415 tts: tts,
416 is_sugared_doc: false,
417 pound_token: pound,
418 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700419 }
Michael Layzell92639a52017-06-01 00:07:44 -0400420 })
421 )
422 |
423 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500424 call!(lit_doc_comment, Comment::Inner),
David Tolnayf800fc12017-12-27 22:08:48 -0500425 |lit| {
426 let span = lit.span;
427 Attribute {
428 style: AttrStyle::Inner(<Token![!]>::new(span)),
429 path: Ident::new("doc", span).into(),
430 tts: vec![
431 eq(span),
432 lit,
433 ].into_iter().collect(),
434 is_sugared_doc: true,
435 pound_token: <Token![#]>::new(span),
436 bracket_token: token::Bracket(span),
437 }
Michael Layzell92639a52017-06-01 00:07:44 -0400438 }
439 )
440 ));
Alex Crichton954046c2017-05-30 21:49:42 -0700441
Michael Layzell92639a52017-06-01 00:07:44 -0400442 named!(pub parse_outer -> Self, alt!(
443 do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800444 pound: punct!(#) >>
Michael Layzell92639a52017-06-01 00:07:44 -0400445 path_and_tts: brackets!(tuple!(
David Tolnaye64213b2017-12-30 00:24:20 -0500446 call!(Path::parse_mod_style),
David Tolnay369f0c52017-12-27 01:50:45 -0500447 syn!(TokenStream)
Michael Layzell92639a52017-06-01 00:07:44 -0400448 )) >>
449 ({
David Tolnay8875fca2017-12-31 13:52:37 -0500450 let (bracket, (path, tts)) = path_and_tts;
Alex Crichton954046c2017-05-30 21:49:42 -0700451
Michael Layzell92639a52017-06-01 00:07:44 -0400452 Attribute {
Alex Crichton954046c2017-05-30 21:49:42 -0700453 style: AttrStyle::Outer,
Michael Layzell92639a52017-06-01 00:07:44 -0400454 path: path,
455 tts: tts,
456 is_sugared_doc: false,
457 pound_token: pound,
458 bracket_token: bracket,
Alex Crichton954046c2017-05-30 21:49:42 -0700459 }
Michael Layzell92639a52017-06-01 00:07:44 -0400460 })
461 )
462 |
463 map!(
David Tolnay201ef212018-01-01 00:09:14 -0500464 call!(lit_doc_comment, Comment::Outer),
David Tolnayf800fc12017-12-27 22:08:48 -0500465 |lit| {
466 let span = lit.span;
467 Attribute {
468 style: AttrStyle::Outer,
469 path: Ident::new("doc", span).into(),
470 tts: vec![
471 eq(span),
472 lit,
473 ].into_iter().collect(),
474 is_sugared_doc: true,
475 pound_token: <Token![#]>::new(span),
476 bracket_token: token::Bracket(span),
477 }
Michael Layzell92639a52017-06-01 00:07:44 -0400478 }
479 )
480 ));
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700481 }
David Tolnayb79ee962016-09-04 09:39:20 -0700482
David Tolnay201ef212018-01-01 00:09:14 -0500483 enum Comment {
484 Inner,
485 Outer,
486 }
487
488 fn lit_doc_comment(input: Cursor, style: Comment) -> PResult<TokenTree> {
Michael Layzell589a8f42017-06-02 19:47:01 -0400489 match input.literal() {
David Tolnay65729482017-12-31 16:14:50 -0500490 Some((span, lit, rest)) => {
David Tolnay201ef212018-01-01 00:09:14 -0500491 let string = lit.to_string();
492 let ok = match style {
David Tolnay61037c62018-01-05 16:21:03 -0800493 Comment::Inner => string.starts_with("//!") || string.starts_with("/*!"),
494 Comment::Outer => string.starts_with("///") || string.starts_with("/**"),
David Tolnay201ef212018-01-01 00:09:14 -0500495 };
496 if ok {
David Tolnay51382052017-12-27 13:46:21 -0500497 Ok((
David Tolnay51382052017-12-27 13:46:21 -0500498 TokenTree {
499 span: span,
David Tolnay360efd22018-01-04 23:35:26 -0800500 kind: TokenNode::Literal(Literal::string(&string)),
David Tolnay51382052017-12-27 13:46:21 -0500501 },
David Tolnayf4aa6b42017-12-31 16:40:33 -0500502 rest,
David Tolnay51382052017-12-27 13:46:21 -0500503 ))
Michael Layzell589a8f42017-06-02 19:47:01 -0400504 } else {
505 parse_error()
506 }
507 }
David Tolnay51382052017-12-27 13:46:21 -0500508 _ => parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700509 }
510 }
David Tolnay9d8f1972016-09-04 11:58:48 -0700511}
David Tolnay87d0b442016-09-04 11:52:12 -0700512
513#[cfg(feature = "printing")]
514mod printing {
515 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500516 use quote::{ToTokens, Tokens};
David Tolnay360efd22018-01-04 23:35:26 -0800517 use proc_macro2::Literal;
David Tolnay87d0b442016-09-04 11:52:12 -0700518
519 impl ToTokens for Attribute {
520 fn to_tokens(&self, tokens: &mut Tokens) {
Arnavion44d2bf32017-04-19 02:47:55 -0700521 // If this was a sugared doc, emit it in its original form instead of `#[doc = "..."]`
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700522 if self.is_sugared_doc {
David Tolnayaaadd782018-01-06 22:58:13 -0800523 if let Some(Meta::NameValue(ref pair)) = self.interpret_meta() {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700524 if pair.ident == "doc" {
David Tolnay360efd22018-01-04 23:35:26 -0800525 if let Lit::Str(ref comment) = pair.lit {
526 tokens.append(TokenTree {
527 span: comment.span,
528 kind: TokenNode::Literal(Literal::doccomment(&comment.value())),
529 });
David Tolnay51382052017-12-27 13:46:21 -0500530 return;
David Tolnay14cbdeb2016-10-01 12:13:59 -0700531 }
David Tolnay4a51dc72016-10-01 00:40:31 -0700532 }
David Tolnayc91dd672016-10-01 01:03:56 -0700533 }
534 }
David Tolnay14cbdeb2016-10-01 12:13:59 -0700535
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700536 self.pound_token.to_tokens(tokens);
537 if let AttrStyle::Inner(ref b) = self.style {
538 b.to_tokens(tokens);
David Tolnay14cbdeb2016-10-01 12:13:59 -0700539 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700540 self.bracket_token.surround(tokens, |tokens| {
541 self.path.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800542 self.tts.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700543 });
David Tolnay87d0b442016-09-04 11:52:12 -0700544 }
545 }
546
David Tolnayaaadd782018-01-06 22:58:13 -0800547 impl ToTokens for MetaList {
David Tolnay87d0b442016-09-04 11:52:12 -0700548 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700549 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700550 self.paren_token.surround(tokens, |tokens| {
551 self.nested.to_tokens(tokens);
552 })
David Tolnay87d0b442016-09-04 11:52:12 -0700553 }
554 }
David Tolnayb7fa2b62016-10-30 10:50:47 -0700555
Alex Crichton62a0a592017-05-22 13:58:53 -0700556 impl ToTokens for MetaNameValue {
David Tolnayb7fa2b62016-10-30 10:50:47 -0700557 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichton62a0a592017-05-22 13:58:53 -0700558 self.ident.to_tokens(tokens);
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700559 self.eq_token.to_tokens(tokens);
Alex Crichton62a0a592017-05-22 13:58:53 -0700560 self.lit.to_tokens(tokens);
David Tolnayb7fa2b62016-10-30 10:50:47 -0700561 }
562 }
David Tolnay87d0b442016-09-04 11:52:12 -0700563}