Skip to main content

wincode_dynamic_derive/
lib.rs

1use {
2    darling::{
3        FromDeriveInput, FromField, FromMeta, FromVariant,
4        ast::{Data, Fields},
5    },
6    proc_macro::TokenStream,
7    std::collections::VecDeque,
8    syn::{
9        DeriveInput, Expr, GenericArgument, Generics, Ident, Path, Type, parse_macro_input,
10        parse_quote,
11        visit::{self, Visit},
12        visit_mut::{self, VisitMut},
13    },
14};
15mod wincode_dynamic;
16
17pub(crate) type ImplBody = Data<Variant, Field>;
18
19#[derive(FromVariant)]
20#[darling(attributes(wincode_dynamic, wincode), forward_attrs)]
21pub(crate) struct Variant {
22    pub(crate) ident: Ident,
23    pub(crate) fields: Fields<Field>,
24    #[darling(default)]
25    pub(crate) tag: Option<Expr>,
26}
27
28#[derive(FromMeta)]
29#[darling(from_word = || Ok(Self::Default))]
30#[allow(dead_code)] // The initializer only needs to be parsed so we accept wincode's full syntax.
31pub(crate) enum SkipMode {
32    Default,
33    DefaultVal(Expr),
34}
35
36#[derive(FromField)]
37#[darling(attributes(wincode_dynamic, wincode))]
38pub(crate) struct Field {
39    pub(crate) ident: Option<Ident>,
40    pub(crate) ty: Type,
41    #[darling(default)]
42    pub(crate) with: Option<Type>,
43    pub(crate) skip: Option<SkipMode>,
44}
45
46impl Field {
47    /// Return the field's wire type, resolving wincode's `_` shorthand from the
48    /// Rust field type.
49    pub(crate) fn target_resolved(&self) -> Type {
50        let Some(with) = &self.with else {
51            return self.ty.clone();
52        };
53        let mut target = with.clone();
54        let mut generic_types = GenericTypes::default();
55        generic_types.visit_type(&self.ty);
56        if generic_types.0.is_empty() {
57            generic_types.0.push_back(self.ty.clone());
58        }
59        InferGeneric(generic_types.0).visit_type_mut(&mut target);
60        target
61    }
62}
63
64/// Generic arguments collected in the same order wincode uses to resolve
65/// adapter placeholders.
66#[derive(Default)]
67struct GenericTypes(VecDeque<Type>);
68
69impl<'ast> Visit<'ast> for GenericTypes {
70    fn visit_generic_argument(&mut self, argument: &'ast GenericArgument) {
71        if let GenericArgument::Type(ty) = argument {
72            match ty {
73                Type::Slice(slice) => {
74                    self.0.push_back((*slice.elem).clone());
75                    return;
76                }
77                Type::Array(array) => {
78                    self.0.push_back((*array.elem).clone());
79                    return;
80                }
81                Type::Path(path)
82                    if path.path.segments.iter().any(|segment| {
83                        matches!(segment.arguments, syn::PathArguments::AngleBracketed(_))
84                    }) => {}
85                _ => self.0.push_back(ty.clone()),
86            }
87        }
88
89        visit::visit_generic_argument(self, argument);
90    }
91}
92
93/// Replaces adapter inference placeholders with the collected field types.
94struct InferGeneric(VecDeque<Type>);
95
96impl VisitMut for InferGeneric {
97    fn visit_generic_argument_mut(&mut self, argument: &mut GenericArgument) {
98        if let GenericArgument::Type(Type::Infer(_)) = argument {
99            *argument = GenericArgument::Type(
100                self.0
101                    .pop_front()
102                    .expect("wincode-dynamic: not enough field types to resolve `_`"),
103            );
104        }
105        visit_mut::visit_generic_argument_mut(self, argument);
106    }
107
108    fn visit_type_array_mut(&mut self, array: &mut syn::TypeArray) {
109        if let Type::Infer(_) = &*array.elem {
110            *array.elem = self
111                .0
112                .pop_front()
113                .expect("wincode-dynamic: not enough field types to resolve `_`");
114        }
115        visit_mut::visit_type_array_mut(self, array);
116    }
117}
118
119#[derive(FromDeriveInput)]
120#[darling(attributes(wincode_dynamic, wincode), forward_attrs)]
121pub(crate) struct Args {
122    pub(crate) ident: Ident,
123    pub(crate) generics: Generics,
124    pub(crate) data: ImplBody,
125
126    /// Helper to determine the crate path.
127    ///
128    /// If `internal` is `true`, the generated code will use the `crate::` path.
129    /// Otherwise, it will use the default crate name path.
130    #[darling(default)]
131    pub(crate) internal: bool,
132    /// Specifies the path to the crate.
133    ///
134    /// Useful when the crate is renamed in `Cargo.toml` or re-exported from
135    /// another module. The path is emitted as written and resolved from the
136    /// derive expansion site.
137    #[darling(rename = "crate", default)]
138    pub(crate) crate_path: Option<Path>,
139    #[darling(default)]
140    pub(crate) tag_encoding: Option<Type>,
141}
142
143impl Args {
144    pub(crate) fn get_crate_name(&self) -> Path {
145        if let Some(crate_path) = &self.crate_path {
146            crate_path.clone()
147        } else if self.internal {
148            parse_quote!(crate)
149        } else {
150            parse_quote!(::wincode_dynamic)
151        }
152    }
153}
154
155#[proc_macro_derive(SchemaDynamic, attributes(wincode_dynamic, wincode))]
156pub fn derive_wincode_dynamic(input: TokenStream) -> TokenStream {
157    let input = parse_macro_input!(input as DeriveInput);
158    match wincode_dynamic::generate(input) {
159        Ok(tokens) => tokens.into(),
160        Err(e) => e.write_errors().into(),
161    }
162}