1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//! # Serde Versions Derive
//! 
//!  `serde_versions_derive` exports an attribute macro that adds versioning support for structs.
//!  
//!  When serializing a named field struct it will automatically add a new field containing the version.
//!  It also allows deserializing the versioned type directly back to the unversioned one.
//!  
//!  Under the hood this works by creating a new struct that wraps the original struct plus adds a version byte field.
//!  Internally this new struct uses `#[serde(flatten)]` to serialize as expected.
//!  The original struct uses `#[serde(to, from)]` to add the version field when serializing and remove it when deserializing.
//!
//! usage: 
//! ```no_run
//! # use serde::{Deserialize, Serialize};
//! # use serde_versions_derive::version;
//! #[version(3)]
//! #[derive(Clone, Serialize, Deserialize)]
//! struct S {
//!     i: i32,
//! }
//! ```
//! 
//! This produces the following
//! ```ignore
//! #[derive(Clone, Serialize, Deserialize)]
//! #[serde(into = "_Sv3", from = "_Sv3")]
//! struct S {
//!     i: i32,
//! }
//! 
//! #[derive(Clone, Serialize, Deserialize)]
//! struct _Sv3 {
//!     version: u8,
//!     #[serde(flatten)]
//!     inner: S
//! }
//! 
//! // plus implementations of To, From and to_versioned() for S
//! ```
//! 
//! Note due to limitations of `#[serde(to, from)]` this does not support structs with type parameters.
//!  

use proc_macro::TokenStream;
use quote::{format_ident, quote};

use syn::{parse::Parser, parse_macro_input, DeriveInput, LitInt};

/// Generate a new struct with a version field and ensure this struct is converted to that form before
/// serialization.
/// 
/// See crate doc for example.
/// 
#[proc_macro_attribute]
pub fn version(attr: TokenStream, item: TokenStream) -> TokenStream {
    let original_ast = parse_macro_input!(item as DeriveInput);

    let mut versioned_ast = original_ast.clone();

    let generics = original_ast.generics.clone();
    let version = parse_macro_input!(attr as LitInt);
    let struct_name = original_ast.ident.clone();
    let struct_name_str = struct_name.to_string();

    // name is old struct name with V<version_number> appended
    let versioned_name = format_ident!("_{}v{}", original_ast.ident, version.to_string());
    let versioned_name_str = versioned_name.to_string();
    versioned_ast.ident = versioned_name.clone();

    // we also need a copy of the original WITHOUT #[serde(into, from)] to prevent a circular dependency
    // Without this it will infinitely recuse as it tries to serialize inner as the versioned which contains inner etc..
    // Unfortunately this adds another type and a bunch of macro generated code but I can't see a way around it at this stage.
    let mut base_ast = original_ast.clone();
    base_ast.ident = format_ident!("_{}Base", original_ast.ident);
    let base_name_string = base_ast.ident.to_string();

    match &mut versioned_ast.data {
        syn::Data::Struct(ref mut struct_data) => {
            match &mut struct_data.fields {
                // drop all the fields and replace with an `inner` and a `version`
                syn::Fields::Named(fields) => {
                    fields.named.clear();
                    fields.named.push(
                        syn::Field::parse_named
                            .parse2(quote! { pub version: u8 })
                            .unwrap(),
                    );
                    fields.named.push(
                        syn::Field::parse_named
                            .parse2(quote! { #[serde(flatten, with = #base_name_string)] pub inner: #struct_name #generics })
                            .unwrap(),
                    );
                }
                _ => (),
            }

            return quote! {
                #[serde(into = #versioned_name_str, from = #versioned_name_str)]
                #original_ast

                #[serde(remote = #struct_name_str)]
                #base_ast

                #versioned_ast

                impl #generics #struct_name #generics {
                    pub fn to_versioned(self) -> #versioned_name #generics {
                        #versioned_name {
                            version: #version,
                            inner: self,
                        }
                    }
                }

                impl #generics std::convert::Into<#versioned_name #generics> for #struct_name #generics {
                    fn into(self) -> #versioned_name #generics {
                        self.to_versioned()
                    }
                }

                impl #generics std::convert::From<#versioned_name #generics> for #struct_name #generics {
                    fn from(s: #versioned_name #generics) -> #struct_name #generics {
                        s.inner
                    }
                }
            }
            .into();
        }
        _ => panic!("`version` has to be used with structs "),
    }
}