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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
// Copyright 2023 James La Novara-Gsell <james.lanovara.gsell@gmail.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Derive functions on an Enum for easily accessing individual items in the Enum.
//! This crate is intended to be used with the [enum-extract-error](https://crates.io/crates/enum-extract-error) crate.
//!
//! # Summary
//!
//! This crate adds a `EnumExtract` derive macro that adds the following functions for each variant in your enum:
//!
//! 1. `is_[variant]`: Returns a bool indicated whether the actual variant matches the expected variant.
//! 2. `as_[variant]`: Returns a Result with a reference to the data contained by the variant, or an error if the actual variant is not the expected variant type.
//! 3. `as_[variant]_mut`: Like `as_[variant]` but returns a mutable reference.
//! 4. `into_[variant]`: Like `as_[variant]` but consumes the value and returns an owned value instead of a reference.
//! 5. `extract_as_[variant]`: Calls `as_[variant]` and returns the data or panics if there was an error.
//! 6. `extract_as_[variant]_mut`: Calls `as_[variant]_mut` and returns the data or panics if there was an error.
//! 7. `extract_into_[variant]`: Calls `into_[variant]` and returns the data or panics if there was an error.
//!
//! ## Notes on the `extract` functions
//!
//! These functions are slightly different from calling `as_[variant]().unwrap()` because they panic with the `Display` output of `EnumExtractError` rather than the `Debug` output.
//!
//! Since these functions can panic they are not recommended for production code.
//! Their main use is in tests, in which they can simplify and flatten tests significantly.
//!
//! # Examples
//!
//! ## Unit Variants
//!
//! Check if the variant is the expected variant:
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum UnitVariants {
//! One,
//! Two,
//! }
//!
//! let unit = UnitVariants::One;
//! assert!(unit.is_one());
//! assert!(!unit.is_two());
//! ```
//!
//! ## Unnamed Variants
//!
//! Check if the variant is the expected variant:
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum UnnamedVariants {
//! One(u32),
//! Two(u32, i32),
//! }
//!
//! let unnamed = UnnamedVariants::One(1);
//! assert!(unnamed.is_one());
//! assert!(!unnamed.is_two());
//! ```
//!
//! Get the variant's value:
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum UnnamedVariants {
//! One(u32),
//! Two(u32, i32),
//! }
//!
//! fn main() -> Result<(), enum_extract_error::EnumExtractError<UnnamedVariants>> {
//! let mut unnamed = UnnamedVariants::One(1);
//!
//! // returns a reference to the value
//! let one = unnamed.as_one()?;
//! assert_eq!(*one, 1);
//!
//! // returns a mutable reference to the value
//! let one = unnamed.as_one_mut()?;
//! assert_eq!(*one, 1);
//!
//! // returns the value by consuming the enum
//! let one = unnamed.into_one()?;
//! assert_eq!(one, 1);
//!
//! Ok(())
//! }
//! ```
//!
//! If the variant has multiple values, a tuple will be returned:
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum UnnamedVariants {
//! One(u32),
//! Two(u32, i32),
//! }
//!
//! fn main() -> Result<(), enum_extract_error::EnumExtractError<UnnamedVariants>> {
//! let mut unnamed = UnnamedVariants::Two(1, 2);
//!
//! // returns a reference to the value
//! let two = unnamed.as_two()?;
//! assert_eq!(two, (&1, &2));
//!
//! // returns a mutable reference to the value
//! let two = unnamed.as_two_mut()?;
//! assert_eq!(two, (&mut 1, &mut 2));
//!
//! // returns the value by consuming the enum
//! let two = unnamed.into_two()?;
//! assert_eq!(two, (1, 2));
//!
//! Ok(())
//! }
//! ```
//!
//! Extract variants of all of the above methods will panic with a decent message if the variant is not the expected variant.
//! Very useful for testing, but not recommended for production code.
//!
//! See the [enum-extract-error](https://crates.io/crates/enum-extract-error) crate for more information on the error type.
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum UnnamedVariants {
//! One(u32),
//! Two(u32, i32),
//! }
//!
//! let mut unnamed = UnnamedVariants::One(1);
//!
//! // returns a reference to the value
//! let one = unnamed.extract_as_one();
//! assert_eq!(*one, 1);
//!
//! // returns a mutable reference to the value
//! let one = unnamed.extract_as_one_mut();
//! assert_eq!(*one, 1);
//!
//! // returns the value by consuming the enum
//! let one = unnamed.extract_into_one();
//! assert_eq!(one, 1);
//! ```
//!
//! ```should_panic
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum UnnamedVariants {
//! One(u32),
//! Two(u32, i32),
//! }
//!
//! let unnamed = UnnamedVariants::One(1);
//!
//! // panics with a decent message
//! let one = unnamed.extract_as_two();
//! ```
//!
//! ## Named Variants
//!
//! Check if the variant is the expected variant:
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum NamedVariants {
//! One {
//! first: u32
//! },
//! Two {
//! first: u32,
//! second: i32
//! },
//! }
//!
//! let named = NamedVariants::One { first: 1 };
//! assert!(named.is_one());
//! assert!(!named.is_two());
//! ```
//!
//! Get the variant's value:
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum NamedVariants {
//! One {
//! first: u32
//! },
//! Two {
//! first: u32,
//! second: i32
//! },
//! }
//!
//! fn main() -> Result<(), enum_extract_error::EnumExtractError<NamedVariants>> {
//! let mut named = NamedVariants::One { first: 1 };
//!
//! // returns a reference to the value
//! let one = named.as_one()?;
//! assert_eq!(*one, 1);
//!
//! // returns a mutable reference to the value
//! let one = named.as_one_mut()?;
//! assert_eq!(*one, 1);
//!
//! // returns the value by consuming the enum
//! let one = named.into_one()?;
//! assert_eq!(one, 1);
//!
//! Ok(())
//! }
//! ```
//!
//! If the variant has multiple values, a tuple will be returned:
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum NamedVariants {
//! One {
//! first: u32
//! },
//! Two {
//! first: u32,
//! second: i32
//! },
//! }
//!
//! fn main() -> Result<(), enum_extract_error::EnumExtractError<NamedVariants>> {
//! let mut unnamed = NamedVariants::Two { first: 1, second: 2 };
//!
//! // returns a reference to the value
//! let two = unnamed.as_two()?;
//! assert_eq!(two, (&1, &2));
//!
//! // returns a mutable reference to the value
//! let two = unnamed.as_two_mut()?;
//! assert_eq!(two, (&mut 1, &mut 2));
//!
//! // returns the value by consuming the enum
//! let two = unnamed.into_two()?;
//! assert_eq!(two, (1, 2));
//!
//! Ok(())
//! }
//! ```
//!
//! Extract variants of all of the above methods will panic with a decent message if the variant is not the expected variant.
//! Very useful for testing, but not recommended for production code.
//!
//! See the [enum-extract-error](https://crates.io/crates/enum-extract-error) crate for more information on the error type.
//!
//! ```rust
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum NamedVariants {
//! One {
//! first: u32
//! },
//! Two {
//! first: u32,
//! second: i32
//! },
//! }
//!
//! let mut named = NamedVariants::One { first: 1 };
//!
//! // returns a reference to the value
//! let one = named.extract_as_one();
//! assert_eq!(*one, 1);
//!
//! // returns a mutable reference to the value
//! let one = named.extract_as_one_mut();
//! assert_eq!(*one, 1);
//!
//! // returns the value by consuming the enum
//! let one = named.extract_into_one();
//! assert_eq!(one, 1);
//! ```
//!
//! ```should_panic
//! use enum_extract_macro::EnumExtract;
//!
//! #[derive(Debug, EnumExtract)]
//! enum NamedVariants {
//! One {
//! first: u32
//! },
//! Two {
//! first: u32,
//! second: i32
//! },
//! }
//!
//! let named = NamedVariants::One { first: 1 };
//!
//! // panics with a decent message
//! let one = named.extract_as_two();
//! ```
#![warn(missing_docs)]
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use syn::{parse_macro_input, DataEnum, DeriveInput};
mod function_def;
mod named_enum_functions;
mod unit_enum_functions;
mod unnamed_enum_functions;
/// Derive functions on an Enum for easily accessing individual items in the Enum
#[proc_macro_derive(EnumExtract, attributes(derive_err))]
pub fn enum_extract(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
// get a usable token stream
let ast: DeriveInput = parse_macro_input!(input as DeriveInput);
let name = &ast.ident;
let generics = &ast.generics;
let enum_data = if let syn::Data::Enum(data) = &ast.data {
data
} else {
panic!("{} is not an enum", name);
};
let mut expanded = TokenStream::new();
// Build the impl
let fns = impl_all_as_fns(name, generics, enum_data);
expanded.extend(fns);
proc_macro::TokenStream::from(expanded)
}
/// Returns an impl block for all of the enum's functions.
fn impl_all_as_fns(enum_name: &Ident, generics: &syn::Generics, data: &DataEnum) -> TokenStream {
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let err_name = syn::Ident::new("EnumExtractError", Span::call_site());
let err_path = syn::Path::from(syn::PathSegment::from(syn::Ident::new(
"enum_extract_error",
Span::call_site(),
)));
let err_type = get_error_type(&err_name, &err_path);
let err_type_with_generics =
get_error_type_with_generics(err_name, err_path, enum_name, generics);
let mut stream = TokenStream::new();
let mut variant_names = TokenStream::new();
for variant_data in &data.variants {
let variant_name = &variant_data.ident;
let tokens = match &variant_data.fields {
syn::Fields::Unit => unit_enum_functions::all_unit_functions(enum_name, variant_name),
syn::Fields::Unnamed(unnamed) => unnamed_enum_functions::all_unnamed_functions(
enum_name,
variant_name,
&err_type,
&err_type_with_generics,
unnamed,
),
syn::Fields::Named(named) => named_enum_functions::all_named_functions(
enum_name,
variant_name,
&err_type,
&err_type_with_generics,
named,
),
};
stream.extend(tokens);
let variant_name = match &variant_data.fields {
syn::Fields::Unit => quote!(Self::#variant_name => stringify!(#variant_name),),
syn::Fields::Unnamed(_) => {
quote!(Self::#variant_name(..) => stringify!(#variant_name),)
}
syn::Fields::Named(_) => quote!(Self::#variant_name{..} => stringify!(#variant_name),),
};
variant_names.extend(variant_name);
}
quote!(
impl #impl_generics #enum_name #ty_generics #where_clause {
#stream
/// Returns the name of the variant.
fn variant_name(&self) -> &'static str {
match self {
#variant_names
_ => unreachable!(),
}
}
}
)
}
/// Returns the error type. ex: `EnumExtractError`
fn get_error_type(err_name: &Ident, err_path: &syn::Path) -> syn::Type {
let err_type = {
let last_segment = syn::PathSegment::from(err_name.clone());
let mut path = err_path.clone();
path.segments.push(last_segment);
syn::Type::Path(syn::TypePath {
qself: None,
path: path,
})
};
err_type
}
/// Returns the error type with generics. ex: `EnumExtractError<T>`
fn get_error_type_with_generics(
err_name: Ident,
err_path: syn::Path,
enum_name: &Ident,
generics: &syn::Generics,
) -> syn::Type {
let err_type_with_generics = {
let mut last_segment = syn::PathSegment::from(err_name.clone());
let mut path = err_path.clone();
let mut inner_type_path = syn::Path::from(syn::PathSegment::from(enum_name.clone()));
let inner_type_segment = inner_type_path.segments.last_mut().unwrap();
let mut generic_args = syn::punctuated::Punctuated::new();
for param in generics.params.iter() {
match param {
syn::GenericParam::Lifetime(lifetime_param) => {
generic_args.push(syn::GenericArgument::Lifetime(syn::Lifetime::new(
&format!("'{}", lifetime_param.lifetime.ident),
Span::call_site(),
)));
}
syn::GenericParam::Const(const_param) => {
generic_args.push(syn::GenericArgument::Const(syn::Expr::Path(
syn::ExprPath {
attrs: vec![],
qself: None,
path: syn::Path::from(syn::PathSegment::from(
const_param.ident.clone(),
)),
},
)));
}
syn::GenericParam::Type(type_param) => {
generic_args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
qself: None,
path: syn::Path::from(syn::PathSegment::from(type_param.ident.clone())),
})));
}
}
}
inner_type_segment.arguments =
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
colon2_token: None,
lt_token: syn::token::Lt::default(),
args: generic_args,
gt_token: syn::token::Gt::default(),
});
last_segment.arguments =
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
colon2_token: None,
lt_token: syn::token::Lt::default(),
args: syn::punctuated::Punctuated::from_iter(vec![syn::GenericArgument::Type(
syn::Type::Path(syn::TypePath {
qself: None,
path: inner_type_path,
}),
)]),
gt_token: syn::token::Gt::default(),
});
path.segments.push(last_segment);
syn::Type::Path(syn::TypePath {
qself: None,
path: path,
})
};
err_type_with_generics
}