| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use proc_macro2::TokenStream; |
| 6 |
use quote::quote; |
| 7 |
use syn::{Attribute, Data, DeriveInput, Field, Fields, Member, Result}; |
| 8 |
|
| 9 |
pub fn expand_as_ref(input: DeriveInput) -> Result<TokenStream> { |
| 10 |
let type_name = &input.ident; |
| 11 |
let st = match input.data { |
| 12 |
Data::Struct(st) => st, |
| 13 |
Data::Enum(_) => return Err(syn::Error::new(input.ident.span(), "Enums not supported")), |
| 14 |
Data::Union(_) => return Err(syn::Error::new(input.ident.span(), "Union not supported")), |
| 15 |
}; |
| 16 |
let mut tokens = TokenStream::default(); |
| 17 |
|
| 18 |
if has_as_ref_attr(&input.attrs) { |
| 19 |
tokens.extend(quote! { |
| 20 |
impl ::std::convert::AsRef<#type_name> for #type_name { |
| 21 |
fn as_ref(&self) -> &#type_name { |
| 22 |
self |
| 23 |
} |
| 24 |
} |
| 25 |
}); |
| 26 |
} |
| 27 |
|
| 28 |
for (m, f) in members_and_fields(&st.fields) { |
| 29 |
if has_as_ref_attr(&f.attrs) { |
| 30 |
let ty = &f.ty; |
| 31 |
tokens.extend(quote! { |
| 32 |
impl ::std::convert::AsRef<#ty> for #type_name { |
| 33 |
fn as_ref(&self) -> &#ty { |
| 34 |
&self.#m |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
}) |
| 39 |
} |
| 40 |
} |
| 41 |
Ok(tokens) |
| 42 |
} |
| 43 |
|
| 44 |
fn members_and_fields(fields: &Fields) -> impl Iterator<Item = (Member, &Field)> { |
| 45 |
fields.iter().enumerate().map(|(idx, f)| { |
| 46 |
let member = match &f.ident { |
| 47 |
Some(ident) => Member::from(ident.clone()), |
| 48 |
None => Member::from(idx), |
| 49 |
}; |
| 50 |
(member, f) |
| 51 |
}) |
| 52 |
} |
| 53 |
|
| 54 |
fn has_as_ref_attr(attrs: &[Attribute]) -> bool { |
| 55 |
attrs.iter().any(|attr| attr.path().is_ident("as_ref")) |
| 56 |
} |