data.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. use crate::attr::Attribute;
  3. use crate::expr::{Expr, Index, Member};
  4. use crate::ident::Ident;
  5. use crate::punctuated::{self, Punctuated};
  6. use crate::restriction::{FieldMutability, Visibility};
  7. use crate::token;
  8. use crate::ty::Type;
  9. ast_struct! {
  10. /// An enum variant.
  11. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  12. pub struct Variant {
  13. pub attrs: Vec<Attribute>,
  14. /// Name of the variant.
  15. pub ident: Ident,
  16. /// Content stored in the variant.
  17. pub fields: Fields,
  18. /// Explicit discriminant: `Variant = 1`
  19. pub discriminant: Option<(Token![=], Expr)>,
  20. }
  21. }
  22. ast_enum_of_structs! {
  23. /// Data stored within an enum variant or struct.
  24. ///
  25. /// # Syntax tree enum
  26. ///
  27. /// This type is a [syntax tree enum].
  28. ///
  29. /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
  30. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  31. pub enum Fields {
  32. /// Named fields of a struct or struct variant such as `Point { x: f64,
  33. /// y: f64 }`.
  34. Named(FieldsNamed),
  35. /// Unnamed fields of a tuple struct or tuple variant such as `Some(T)`.
  36. Unnamed(FieldsUnnamed),
  37. /// Unit struct or unit variant such as `None`.
  38. Unit,
  39. }
  40. }
  41. ast_struct! {
  42. /// Named fields of a struct or struct variant such as `Point { x: f64,
  43. /// y: f64 }`.
  44. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  45. pub struct FieldsNamed {
  46. pub brace_token: token::Brace,
  47. pub named: Punctuated<Field, Token![,]>,
  48. }
  49. }
  50. ast_struct! {
  51. /// Unnamed fields of a tuple struct or tuple variant such as `Some(T)`.
  52. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  53. pub struct FieldsUnnamed {
  54. pub paren_token: token::Paren,
  55. pub unnamed: Punctuated<Field, Token![,]>,
  56. }
  57. }
  58. impl Fields {
  59. /// Get an iterator over the borrowed [`Field`] items in this object. This
  60. /// iterator can be used to iterate over a named or unnamed struct or
  61. /// variant's fields uniformly.
  62. pub fn iter(&self) -> punctuated::Iter<Field> {
  63. match self {
  64. Fields::Unit => crate::punctuated::empty_punctuated_iter(),
  65. Fields::Named(f) => f.named.iter(),
  66. Fields::Unnamed(f) => f.unnamed.iter(),
  67. }
  68. }
  69. /// Get an iterator over the mutably borrowed [`Field`] items in this
  70. /// object. This iterator can be used to iterate over a named or unnamed
  71. /// struct or variant's fields uniformly.
  72. pub fn iter_mut(&mut self) -> punctuated::IterMut<Field> {
  73. match self {
  74. Fields::Unit => crate::punctuated::empty_punctuated_iter_mut(),
  75. Fields::Named(f) => f.named.iter_mut(),
  76. Fields::Unnamed(f) => f.unnamed.iter_mut(),
  77. }
  78. }
  79. /// Returns the number of fields.
  80. pub fn len(&self) -> usize {
  81. match self {
  82. Fields::Unit => 0,
  83. Fields::Named(f) => f.named.len(),
  84. Fields::Unnamed(f) => f.unnamed.len(),
  85. }
  86. }
  87. /// Returns `true` if there are zero fields.
  88. pub fn is_empty(&self) -> bool {
  89. match self {
  90. Fields::Unit => true,
  91. Fields::Named(f) => f.named.is_empty(),
  92. Fields::Unnamed(f) => f.unnamed.is_empty(),
  93. }
  94. }
  95. return_impl_trait! {
  96. /// Get an iterator over the fields of a struct or variant as [`Member`]s.
  97. /// This iterator can be used to iterate over a named or unnamed struct or
  98. /// variant's fields uniformly.
  99. ///
  100. /// # Example
  101. ///
  102. /// The following is a simplistic [`Clone`] derive for structs. (A more
  103. /// complete implementation would additionally want to infer trait bounds on
  104. /// the generic type parameters.)
  105. ///
  106. /// ```
  107. /// # use quote::quote;
  108. /// #
  109. /// fn derive_clone(input: &syn::ItemStruct) -> proc_macro2::TokenStream {
  110. /// let ident = &input.ident;
  111. /// let members = input.fields.members();
  112. /// let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
  113. /// quote! {
  114. /// impl #impl_generics Clone for #ident #ty_generics #where_clause {
  115. /// fn clone(&self) -> Self {
  116. /// Self {
  117. /// #(#members: self.#members.clone()),*
  118. /// }
  119. /// }
  120. /// }
  121. /// }
  122. /// }
  123. /// ```
  124. ///
  125. /// For structs with named fields, it produces an expression like `Self { a:
  126. /// self.a.clone() }`. For structs with unnamed fields, `Self { 0:
  127. /// self.0.clone() }`. And for unit structs, `Self {}`.
  128. pub fn members(&self) -> impl Iterator<Item = Member> + Clone + '_ [Members] {
  129. Members {
  130. fields: self.iter(),
  131. index: 0,
  132. }
  133. }
  134. }
  135. }
  136. impl IntoIterator for Fields {
  137. type Item = Field;
  138. type IntoIter = punctuated::IntoIter<Field>;
  139. fn into_iter(self) -> Self::IntoIter {
  140. match self {
  141. Fields::Unit => Punctuated::<Field, ()>::new().into_iter(),
  142. Fields::Named(f) => f.named.into_iter(),
  143. Fields::Unnamed(f) => f.unnamed.into_iter(),
  144. }
  145. }
  146. }
  147. impl<'a> IntoIterator for &'a Fields {
  148. type Item = &'a Field;
  149. type IntoIter = punctuated::Iter<'a, Field>;
  150. fn into_iter(self) -> Self::IntoIter {
  151. self.iter()
  152. }
  153. }
  154. impl<'a> IntoIterator for &'a mut Fields {
  155. type Item = &'a mut Field;
  156. type IntoIter = punctuated::IterMut<'a, Field>;
  157. fn into_iter(self) -> Self::IntoIter {
  158. self.iter_mut()
  159. }
  160. }
  161. ast_struct! {
  162. /// A field of a struct or enum variant.
  163. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  164. pub struct Field {
  165. pub attrs: Vec<Attribute>,
  166. pub vis: Visibility,
  167. pub mutability: FieldMutability,
  168. /// Name of the field, if any.
  169. ///
  170. /// Fields of tuple structs have no names.
  171. pub ident: Option<Ident>,
  172. pub colon_token: Option<Token![:]>,
  173. pub ty: Type,
  174. }
  175. }
  176. pub struct Members<'a> {
  177. fields: punctuated::Iter<'a, Field>,
  178. index: u32,
  179. }
  180. impl<'a> Iterator for Members<'a> {
  181. type Item = Member;
  182. fn next(&mut self) -> Option<Self::Item> {
  183. let field = self.fields.next()?;
  184. let member = match &field.ident {
  185. Some(ident) => Member::Named(ident.clone()),
  186. None => {
  187. #[cfg(all(feature = "parsing", feature = "printing"))]
  188. let span = crate::spanned::Spanned::span(&field.ty);
  189. #[cfg(not(all(feature = "parsing", feature = "printing")))]
  190. let span = proc_macro2::Span::call_site();
  191. Member::Unnamed(Index {
  192. index: self.index,
  193. span,
  194. })
  195. }
  196. };
  197. self.index += 1;
  198. Some(member)
  199. }
  200. }
  201. impl<'a> Clone for Members<'a> {
  202. fn clone(&self) -> Self {
  203. Members {
  204. fields: self.fields.clone(),
  205. index: self.index,
  206. }
  207. }
  208. }
  209. #[cfg(feature = "parsing")]
  210. pub(crate) mod parsing {
  211. use crate::attr::Attribute;
  212. use crate::data::{Field, Fields, FieldsNamed, FieldsUnnamed, Variant};
  213. use crate::error::Result;
  214. use crate::expr::Expr;
  215. use crate::ext::IdentExt as _;
  216. use crate::ident::Ident;
  217. #[cfg(not(feature = "full"))]
  218. use crate::parse::discouraged::Speculative as _;
  219. use crate::parse::{Parse, ParseStream};
  220. use crate::restriction::{FieldMutability, Visibility};
  221. #[cfg(not(feature = "full"))]
  222. use crate::scan_expr::scan_expr;
  223. use crate::token;
  224. use crate::ty::Type;
  225. use crate::verbatim;
  226. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  227. impl Parse for Variant {
  228. fn parse(input: ParseStream) -> Result<Self> {
  229. let attrs = input.call(Attribute::parse_outer)?;
  230. let _visibility: Visibility = input.parse()?;
  231. let ident: Ident = input.parse()?;
  232. let fields = if input.peek(token::Brace) {
  233. Fields::Named(input.parse()?)
  234. } else if input.peek(token::Paren) {
  235. Fields::Unnamed(input.parse()?)
  236. } else {
  237. Fields::Unit
  238. };
  239. let discriminant = if input.peek(Token![=]) {
  240. let eq_token: Token![=] = input.parse()?;
  241. #[cfg(feature = "full")]
  242. let discriminant: Expr = input.parse()?;
  243. #[cfg(not(feature = "full"))]
  244. let discriminant = {
  245. let begin = input.fork();
  246. let ahead = input.fork();
  247. let mut discriminant: Result<Expr> = ahead.parse();
  248. if discriminant.is_ok() {
  249. input.advance_to(&ahead);
  250. } else if scan_expr(input).is_ok() {
  251. discriminant = Ok(Expr::Verbatim(verbatim::between(&begin, input)));
  252. }
  253. discriminant?
  254. };
  255. Some((eq_token, discriminant))
  256. } else {
  257. None
  258. };
  259. Ok(Variant {
  260. attrs,
  261. ident,
  262. fields,
  263. discriminant,
  264. })
  265. }
  266. }
  267. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  268. impl Parse for FieldsNamed {
  269. fn parse(input: ParseStream) -> Result<Self> {
  270. let content;
  271. Ok(FieldsNamed {
  272. brace_token: braced!(content in input),
  273. named: content.parse_terminated(Field::parse_named, Token![,])?,
  274. })
  275. }
  276. }
  277. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  278. impl Parse for FieldsUnnamed {
  279. fn parse(input: ParseStream) -> Result<Self> {
  280. let content;
  281. Ok(FieldsUnnamed {
  282. paren_token: parenthesized!(content in input),
  283. unnamed: content.parse_terminated(Field::parse_unnamed, Token![,])?,
  284. })
  285. }
  286. }
  287. impl Field {
  288. /// Parses a named (braced struct) field.
  289. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  290. pub fn parse_named(input: ParseStream) -> Result<Self> {
  291. let attrs = input.call(Attribute::parse_outer)?;
  292. let vis: Visibility = input.parse()?;
  293. let unnamed_field = cfg!(feature = "full") && input.peek(Token![_]);
  294. let ident = if unnamed_field {
  295. input.call(Ident::parse_any)
  296. } else {
  297. input.parse()
  298. }?;
  299. let colon_token: Token![:] = input.parse()?;
  300. let ty: Type = if unnamed_field
  301. && (input.peek(Token![struct])
  302. || input.peek(Token![union]) && input.peek2(token::Brace))
  303. {
  304. let begin = input.fork();
  305. input.call(Ident::parse_any)?;
  306. input.parse::<FieldsNamed>()?;
  307. Type::Verbatim(verbatim::between(&begin, input))
  308. } else {
  309. input.parse()?
  310. };
  311. Ok(Field {
  312. attrs,
  313. vis,
  314. mutability: FieldMutability::None,
  315. ident: Some(ident),
  316. colon_token: Some(colon_token),
  317. ty,
  318. })
  319. }
  320. /// Parses an unnamed (tuple struct) field.
  321. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  322. pub fn parse_unnamed(input: ParseStream) -> Result<Self> {
  323. Ok(Field {
  324. attrs: input.call(Attribute::parse_outer)?,
  325. vis: input.parse()?,
  326. mutability: FieldMutability::None,
  327. ident: None,
  328. colon_token: None,
  329. ty: input.parse()?,
  330. })
  331. }
  332. }
  333. }
  334. #[cfg(feature = "printing")]
  335. mod printing {
  336. use crate::data::{Field, FieldsNamed, FieldsUnnamed, Variant};
  337. use crate::print::TokensOrDefault;
  338. use proc_macro2::TokenStream;
  339. use quote::{ToTokens, TokenStreamExt};
  340. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  341. impl ToTokens for Variant {
  342. fn to_tokens(&self, tokens: &mut TokenStream) {
  343. tokens.append_all(&self.attrs);
  344. self.ident.to_tokens(tokens);
  345. self.fields.to_tokens(tokens);
  346. if let Some((eq_token, disc)) = &self.discriminant {
  347. eq_token.to_tokens(tokens);
  348. disc.to_tokens(tokens);
  349. }
  350. }
  351. }
  352. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  353. impl ToTokens for FieldsNamed {
  354. fn to_tokens(&self, tokens: &mut TokenStream) {
  355. self.brace_token.surround(tokens, |tokens| {
  356. self.named.to_tokens(tokens);
  357. });
  358. }
  359. }
  360. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  361. impl ToTokens for FieldsUnnamed {
  362. fn to_tokens(&self, tokens: &mut TokenStream) {
  363. self.paren_token.surround(tokens, |tokens| {
  364. self.unnamed.to_tokens(tokens);
  365. });
  366. }
  367. }
  368. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  369. impl ToTokens for Field {
  370. fn to_tokens(&self, tokens: &mut TokenStream) {
  371. tokens.append_all(&self.attrs);
  372. self.vis.to_tokens(tokens);
  373. if let Some(ident) = &self.ident {
  374. ident.to_tokens(tokens);
  375. TokensOrDefault(&self.colon_token).to_tokens(tokens);
  376. }
  377. self.ty.to_tokens(tokens);
  378. }
  379. }
  380. }