oxedyne/fe2o3/fe2o3_core/new/src/lib.rs
2.1 KiB, 3 runs
created by r1870400018:58, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Derive macro for generating a `new` constructor function. |
| 2 | //! |
| 3 | //! This crate provides a derive macro that automatically implements a `new` constructor |
| 4 | //! for structs. The generated constructor takes all fields as parameters in the order |
| 5 | //! they are declared and creates a new instance of the struct. |
| 6 | //! |
| 7 | //! # Example |
| 8 | //! |
| 9 | //! ```rust |
| 10 | //! use oxedyne_fe2o3_core_new::New; |
| 11 | //! |
| 12 | //! #[derive(New)] |
| 13 | //! struct Person { |
| 14 | //! name: String, |
| 15 | //! age: u32, |
| 16 | //! } |
| 17 | //! |
| 18 | //! // The macro generates: |
| 19 | //! // impl Person { |
| 20 | //! // pub fn new(name: String, age: u32) -> Self { |
| 21 | //! // Self { name, age } |
| 22 | //! // } |
| 23 | //! // } |
| 24 | //! |
| 25 | //! let person = Person::new(String::from("Alice"), 30); |
| 26 | //! ``` |
| 27 | //! |
| 28 | //! # Limitations |
| 29 | //! |
| 30 | //! - Only works on structs with named fields |
| 31 | //! - Does not support default values for fields |
| 32 | //! - Does not support field-level attributes |
| 33 | use proc_macro::TokenStream; |
| 34 | use quote::quote; |
| 35 | use syn::{parse_macro_input, DeriveInput, Fields}; |
| 36 | |
| 37 | |
| 38 | #[proc_macro_derive(New)] |
| 39 | pub fn derive_new(input: TokenStream) -> TokenStream { |
| 40 | // Parse the input tokens into a syntax tree |
| 41 | let input = parse_macro_input!(input as DeriveInput); |
| 42 | let name = &input.ident; |
| 43 | |
| 44 | // Extract the fields from the struct |
| 45 | let fields = match &input.data { |
| 46 | syn::Data::Struct(data) => { |
| 47 | match &data.fields { |
| 48 | Fields::Named(fields) => &fields.named, |
| 49 | _ => panic!("Only named fields are supported") |
| 50 | } |
| 51 | }, |
| 52 | _ => panic!("Only structs are supported") |
| 53 | }; |
| 54 | |
| 55 | // Generate the parameter list and field initialization |
| 56 | let params = fields.iter().map(|f| { |
| 57 | let name = &f.ident; |
| 58 | let ty = &f.ty; |
| 59 | quote! { #name: #ty } |
| 60 | }); |
| 61 | |
| 62 | let field_inits = fields.iter().map(|f| { |
| 63 | let name = &f.ident; |
| 64 | quote! { #name } |
| 65 | }); |
| 66 | |
| 67 | // Generate the implementation |
| 68 | let expanded = quote! { |
| 69 | impl #name { |
| 70 | pub fn new(#(#params),*) -> Self { |
| 71 | Self { |
| 72 | #(#field_inits),* |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | }; |
| 77 | |
| 78 | TokenStream::from(expanded) |
| 79 | } |