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
//! # Persitent Structs
//!
//! A small derive Macro for structs, that generates a `with_<name>` and `update_<name>`
//! method for each field of a struct, e.g:
//!
//! ```rust
//! use persistent_structs::PersistentStruct;
//!
//! #[derive(PersistentStruct, PartialEq)]
//! struct Foo {
//!     pub foo: u8,
//! }
//!
//! fn main() {
//!     let foo = Foo { foo: 1 };
//!     let foo = foo.with_foo(5);
//!     assert!(foo == Foo { foo: 5 });
//!
//!     let foo = foo.update_foo(|x| x + 1);
//!     assert!(foo.foo == 6);
//! }
//! ```

use proc_macro::TokenStream;
use quote::format_ident;
use syn::{parse_macro_input, DeriveInput, Field, ItemFn};

#[proc_macro_derive(PersistentStruct)]
pub fn derive_persistent_struct(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let syn::Data::Struct(data) = &input.data else {
        panic!("PersistentStruct may only be used with structs");
    };

    let syn::Fields::Named(named_fields) = &data.fields else {
        panic!("PersistentStruct may only be Used on structs with named fields");
    };

    let set_functions = named_fields.named.iter().map(|f: &Field| -> ItemFn {
        let vis = &f.vis;
        let field_name = f.ident.as_ref().expect("Fields must have a name");
        let ident = format_ident!("with_{}", field_name);
        let ty = &f.ty;

        syn::parse_quote! {
            #vis fn #ident(self, x: #ty) -> Self {
                Self {
                    #field_name: x,
                    ..self
                }
            }
        }
    });

    let update_functions = named_fields.named.iter().map(|f: &Field| -> ItemFn {
        let vis = &f.vis;
        let field_name = f.ident.as_ref().expect("Fields must have a name");
        let ident = format_ident!("update_{}", field_name);
        let ty = &f.ty;

        syn::parse_quote! {
            #vis fn #ident(self, f: impl FnOnce(#ty) -> #ty) -> Self {
                Self {
                    #field_name: f(self.#field_name),
                    ..self
                }
            }
        }
    });

    let name = &input.ident;
    let generics = &input.generics;

    quote::quote! {
        impl #generics #name #generics {
            #(#set_functions)*
            #(#update_functions)*
        }
    }
    .into()
}