persistent_structs/
lib.rs

1//! # Persitent Structs
2//!
3//! A small derive Macro for structs, that generates a `with_<name>` and `update_<name>`
4//! method for each field of a struct, e.g:
5//!
6//! ```rust
7//! use persistent_structs::PersistentStruct;
8//!
9//! #[derive(PersistentStruct, PartialEq)]
10//! struct Foo {
11//!     pub foo: u8,
12//! }
13//!
14//! fn main() {
15//!     let foo = Foo { foo: 1 };
16//!     let foo = foo.with_foo(5);
17//!     assert!(foo == Foo { foo: 5 });
18//!
19//!     let foo = foo.update_foo(|x| x + 1);
20//!     assert!(foo.foo == 6);
21//! }
22//! ```
23
24use proc_macro::TokenStream;
25use quote::format_ident;
26use syn::{parse_macro_input, DeriveInput, Field, ItemFn};
27
28#[proc_macro_derive(PersistentStruct)]
29pub fn derive_persistent_struct(input: TokenStream) -> TokenStream {
30    let input = parse_macro_input!(input as DeriveInput);
31
32    let syn::Data::Struct(data) = &input.data else {
33        panic!("PersistentStruct may only be used with structs");
34    };
35
36    let syn::Fields::Named(named_fields) = &data.fields else {
37        panic!("PersistentStruct may only be Used on structs with named fields");
38    };
39
40    let set_functions = named_fields.named.iter().map(|f: &Field| -> ItemFn {
41        let vis = &f.vis;
42        let field_name = f.ident.as_ref().expect("Fields must have a name");
43        let ident = format_ident!("with_{}", field_name);
44        let ty = &f.ty;
45
46        syn::parse_quote! {
47            #vis fn #ident(self, x: #ty) -> Self {
48                Self {
49                    #field_name: x,
50                    ..self
51                }
52            }
53        }
54    });
55
56    let update_functions = named_fields.named.iter().map(|f: &Field| -> ItemFn {
57        let vis = &f.vis;
58        let field_name = f.ident.as_ref().expect("Fields must have a name");
59        let ident = format_ident!("update_{}", field_name);
60        let ty = &f.ty;
61
62        syn::parse_quote! {
63            #vis fn #ident(self, f: impl FnOnce(#ty) -> #ty) -> Self {
64                Self {
65                    #field_name: f(self.#field_name),
66                    ..self
67                }
68            }
69        }
70    });
71
72    let name = &input.ident;
73    let generics = &input.generics;
74
75    quote::quote! {
76        impl #generics #name #generics {
77            #(#set_functions)*
78            #(#update_functions)*
79        }
80    }
81    .into()
82}