1use syn::spanned::Spanned;
2use syn::{Field, Ident, Meta};
34use crate::ast::Data;
5use crate::codegen::ForwardAttrs;
6use crate::options::{
7 Core, DefaultExpression, ForwardAttrsFilter, ForwardedField, ParseAttribute, ParseData,
8};
9use crate::util::PathList;
10use crate::{Error, FromField, FromMeta, Result};
1112/// Reusable base for `FromDeriveInput`, `FromVariant`, `FromField`, and other top-level
13/// `From*` traits.
14#[derive(Debug, Clone)]
15pub struct OuterFrom {
16/// The field on the target struct which should receive the type identifier, if any.
17pub ident: Option<Ident>,
1819/// The field on the target struct which should receive the type attributes, if any.
20pub attrs: Option<ForwardedField>,
2122pub container: Core,
2324/// The attribute names that should be searched.
25pub attr_names: PathList,
2627/// The attribute names that should be forwarded. The presence of the word with no additional
28 /// filtering will cause _all_ attributes to be cloned and exposed to the struct after parsing.
29pub forward_attrs: Option<ForwardAttrsFilter>,
3031/// Whether or not the container can be made through conversion from the type `Ident`.
32pub from_ident: bool,
33}
3435impl OuterFrom {
36pub fn start(di: &syn::DeriveInput) -> Result<Self> {
37Ok(OuterFrom {
38 container: Core::start(di)?,
39 attrs: Default::default(),
40 ident: Default::default(),
41 attr_names: Default::default(),
42 forward_attrs: Default::default(),
43 from_ident: Default::default(),
44 })
45 }
4647pub fn as_forward_attrs(&self) -> ForwardAttrs<'_> {
48 ForwardAttrs {
49 field: self.attrs.as_ref(),
50 filter: self.forward_attrs.as_ref(),
51 }
52 }
53}
5455impl ParseAttribute for OuterFrom {
56fn parse_nested(&mut self, mi: &Meta) -> Result<()> {
57let path = mi.path();
58if path.is_ident("attributes") {
59self.attr_names = FromMeta::from_meta(mi)?;
60 } else if path.is_ident("forward_attrs") {
61self.forward_attrs = FromMeta::from_meta(mi)?;
62 } else if path.is_ident("from_ident") {
63// HACK: Declaring that a default is present will cause fields to
64 // generate correct code, but control flow isn't that obvious.
65self.container.default = Some(DefaultExpression::Trait {
66// Use the span of the `from_ident` keyword so that errors in generated code
67 // caused by this will point back to the correct location.
68span: path.span(),
69 });
70self.from_ident = true;
71 } else {
72return self.container.parse_nested(mi);
73 }
74Ok(())
75 }
76}
7778impl ParseData for OuterFrom {
79fn parse_field(&mut self, field: &Field) -> Result<()> {
80match field.ident.as_ref().map(|v| v.to_string()).as_deref() {
81Some("ident") => {
82self.ident.clone_from(&field.ident);
83Ok(())
84 }
85Some("attrs") => {
86self.attrs = ForwardedField::from_field(field).map(Some)?;
87Ok(())
88 }
89_ => self.container.parse_field(field),
90 }
91 }
9293fn validate_body(&self, errors: &mut crate::error::Accumulator) {
94self.container.validate_body(errors);
95if let Some(attrs) = &self.attrs {
96if self.forward_attrs.is_none() {
97let container_name = match &self.container.data {
98 Data::Enum(_) => "enum",
99 Data::Struct(_) => "struct",
100 };
101 errors.push(
102 Error::custom(format!(
103"field will not be populated because `forward_attrs` is not set on the {}",
104 container_name
105 ))
106 .with_span(&attrs.ident),
107 );
108 }
109 }
110 }
111}