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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
//! Attribute macro to define enum by differences of variants with useful accessors //! //! This is a small Rust library provides one attribute macro `#[diff_enum::common_fields]` to help defining //! `enum` variants by their differences. It is useful when you need to handle data which are almost the //! same, but different partially. //! //! By the attribute macro, common fields among all variants and different fields for each variant can //! be defined separately. Common fields are defined once. Additionally accessor methods for common fields //! are automatically defined. //! //! For example, //! //! ```rust //! extern crate diff_enum; //! use diff_enum::common_fields; //! //! #[common_fields { //! user: String, //! name: String, //! stars: u32, //! issues: u32, //! }] //! #[derive(Debug)] //! enum RemoteRepo { //! GitHub { //! language: String, //! pull_requests: u32, //! }, //! GitLab { //! merge_requests: u32, //! }, //! } //! # let repo = RemoteRepo::GitHub { //! # user: "rust-lang".to_string(), //! # name: "rust".to_string(), //! # language: "rust".to_string(), //! # issues: 4536, //! # pull_requests: 129, //! # stars: 33679, //! # }; //! //! # println!("User: {}", repo.user()); //! ``` //! //! is expanded to //! //! ```rust,ignore //! #[derive(Debug)] //! enum RemoteRepo { //! GitHub { //! language: String, //! pull_requests: u32, //! user: String, //! name: String, //! stars: u32, //! issues: u32, //! }, //! GitLab { //! merge_requests: u32, //! user: String, //! name: String, //! stars: u32, //! issues: u32, //! }, //! } //! ``` //! //! Additionally, accessor functions are defined for common fields. For example, //! //! ```rust //! # extern crate diff_enum; //! # use diff_enum::common_fields; //! //! # #[common_fields { //! # user: String, //! # name: String, //! # stars: u32, //! # issues: u32, //! # }] //! # #[derive(Debug)] //! # enum RemoteRepo { //! # GitHub { //! # language: String, //! # pull_requests: u32, //! # }, //! # GitLab { //! # merge_requests: u32, //! # }, //! # } //! let repo = RemoteRepo::GitHub { //! user: "rust-lang".to_string(), //! name: "rust".to_string(), //! language: "rust".to_string(), //! issues: 4536, //! pull_requests: 129, //! stars: 33679, //! }; //! //! println!("User: {}", repo.user()); //! ``` //! //! //! //! ## Alternative //! //! Without this crate, it's typical to separate the data into a struct with common fields and a enum //! variants for differences. //! //! For above `RemoteRepo` example, //! //! ```rust,ignore //! enum RemoteRepoKind { //! GitHub { //! language: String, //! pull_requests: u32, //! }, //! GitLab { //! merge_requests: u32, //! }, //! } //! struct RemoteRepo { //! user: String, //! name: String, //! stars: u32, //! issues: u32, //! kind: RemoteRepoKind, //! } //! ``` //! //! This solution has problems as follows: //! //! - Fields are split into 2 parts for the reason of Rust enum. Essentially number of issues and number //! of pull requests are both properties of a GitHub repository. As natural data structure they should //! be in the same flat struct. //! - Naming the inner enum is difficult. Here I used 'Kind' to separate parts. But is it appropriate? //! 'Kind' is too generic name with weak meaning. The weak name comes from awkwardness of the data //! structure. //! //! ## Usage //! //! At first, please load the crate. //! //! ```rust,irgnore //! extern crate diff_enum; //! use diff_enum::common_fields; //! ``` //! //! And use `#[common_fields]` attribute macro for your enum definitions. //! //! ```ignore //! #[common_fields { //! common fields here... //! }] //! enum ... //! ``` //! //! or fully qualified name if you like //! //! ```ignore //! #[diff_enum::common_fields { //! common fields here... //! }] //! enum ... //! ``` //! //! Any attributes and comments can be put to the common fields as normal `enum` fields. //! //! Accessor methods corresponding to common fields are defined. It is a useful helper to access common //! fields without using pattern match. //! //! For example, //! //! ```rust,ignore //! #[common_fields { i: i32 }] //! enum E { A, B{ b: bool } } //! ``` //! //! Generates an accessor method for `i` as follows: //! //! ```rust,ignore //! impl E { //! fn i(&self) -> &i32 { //! match self { //! E::A{ref i, ..} => i, //! E::B{ref i, ..} => i, //! } //! } //! } //! ``` //! //! ## Errors //! //! The attribute macro causes compilation errors in the following cases. //! //! - When no common field is put //! - When fields in attribute argument is not form of `field: type` //! - When `#[common_fields {...}]` is set to other than `enum` definitions //! - When tuple style enum variant is used in `enum` definition extern crate proc_macro; extern crate proc_macro2; extern crate quote; extern crate syn; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use proc_macro_attribute; use quote::quote; use syn::{Data, DeriveInput, Fields, FieldsNamed, Ident}; #[proc_macro_attribute] pub fn common_fields(attr: TokenStream, item: TokenStream) -> TokenStream { let shared: FieldsNamed = parse_shared_fields(attr); if shared.named.is_empty() { panic!("No shared field is set to #[diff_enum::common_fields]"); } let input: DeriveInput = match syn::parse(item) { Ok(parsed) => parsed, Err(err) => panic!( "#[diff_enum::common_fields] only can be set at enum definition: {}", err ), }; let impl_accessors = generate_accessors(&shared, &input, input.ident.clone()); let expanded_enum = expand_shared_fields(&shared, input); let tokens = quote! { #expanded_enum #impl_accessors }; tokens.into() } fn parse_shared_fields(attr: TokenStream) -> FieldsNamed { use proc_macro::{Delimiter, Group, TokenTree}; let braced = TokenStream::from(TokenTree::Group(Group::new(Delimiter::Brace, attr))); match syn::parse(braced) { Ok(fields) => fields, Err(err) => panic!( "Cannot parse fields in attributes at #[diff_enum::common_fields]: {}", err ), } } fn expand_shared_fields(shared: &FieldsNamed, mut input: DeriveInput) -> TokenStream2 { let mut enum_ = match input.data { Data::Enum(e) => e, _ => panic!("#[diff_enum::common_fields] can be set at only enum"), }; for variant in enum_.variants.iter_mut() { match variant.fields { Fields::Named(ref mut f) => { for shared_field in shared.named.iter() { f.named.push(shared_field.clone()); } } Fields::Unnamed(_) => panic!( "#[diff_enum::common_fields] cannot mix named fields with unnamed fields at enum variant {}", variant.ident.to_string() ), Fields::Unit => { variant.fields = Fields::Named(shared.clone()); } } } input.data = Data::Enum(enum_); quote!(#input) } fn generate_accessors(shared: &FieldsNamed, input: &DeriveInput, enum_name: Ident) -> TokenStream2 { let variants = match input.data { Data::Enum(ref e) => &e.variants, _ => panic!("#[diff_enum::common_fields] can be set at only enum"), }; let accessors = shared.named.iter().map(|field| { let field_name = &field.ident; let ty = &field.ty; let arms = variants.iter().map(|variant| { let ident = &variant.ident; quote! { #enum_name::#ident{ref #field_name, ..} => #field_name, } }); quote! { #[inline] #[allow(dead_code)] pub fn #field_name (&self) -> &#ty { match self { #( #arms )* } } } }); quote! { impl #enum_name { #( #accessors )* } } }